問題描述
如何正確附加到在功能組件中作為道具傳遞的字符串數組 (How to properly append to string array that was passed as props in functional component)
我有一個父組件,它定義了一個字符串數組的 useState 鉤子。然後我有一個需要更新字符串數組的子組件,所以我同時傳遞了字符串數組和 useState 的函數來更新它。但是,當我嘗試引用 props 數組時,解釋器會抱怨(參見代碼/註釋):
ParentComponent.tsx:
import React, { useState } from 'react';
import { ChildComponent } from './ChildComponent';
export function ParentComponent() {
const [log, setLog] = useState<string[]>([]);
return(
<ChildComponent log={log} setLog={setLog} />
);
};
ChildComponent.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>
);
};
我做錯了什麼?
參考解法
方法 1:
setLog: Function
is not precise enough. You need:
interface Props {
log: string[],
setLog: React.Dispatch<React.SetStateAction<Array<string>>>
};
And this
props.setLog(props.log => [...props.log, "Loaded child component."]);
should be
props.setLog(previousLog => [...previousLog, "Loaded child component."]);
Or, in this case, it looks like it'll always have the current value of the log in the prop‑closure when this line runs, so it can be simplified to
props.setLog([...props.log, "Loaded child component."]);
(by Brian Reading、CertainPerformance)