【发布时间】:2021-05-14 16:34:18
【问题描述】:
我有一个父组件,它定义了一个字符串数组的 useState 挂钩。然后我有一个需要更新字符串数组的子组件,所以我同时传递了字符串数组和 useState 的函数来更新它。但是,当我尝试引用 props 数组时,解释器会抱怨(参见代码/cmets):
父组件.tsx:
import React, { useState } from 'react';
import { ChildComponent } from './ChildComponent';
export function ParentComponent() {
const [log, setLog] = useState<string[]>([]);
return(
<ChildComponent log={log} setLog={setLog} />
);
};
子组件.tsx
import React, { useEffect } from 'react';
interface Props {
log: string[],
setLog: Function
};
export function ChildComponent(props: Props) {
useEffect(() => {
/* I typically use this pattern to append to an array in a useState hook:
setArray(array => [...array, "String to append"]);
so I try to use this with the props as well: */
props.setLog(props.log => [...props.log, "Loaded child component."]); // Interpreter complains at arrow: ',' expected. ts(1005)
},[]);
return (
<div>
{props.log.map(logItem => <p key={logItem}>{logItem}</p>)}
</div>
);
};
我做错了什么?
【问题讨论】:
标签: reactjs typescript react-hooks use-state