如何正确附加到在功能组件中作为道具传递的字符串数组
How to properly append to string array that was passed as props in functional component
我有一个父组件,它定义了一个 useState 挂钩,它是一个字符串数组。然后我有一个需要更新字符串数组的子组件,所以我传递了字符串数组和 useState 的函数来更新它。但是,当我尝试引用 props 数组时,解释器抱怨(参见 code/comments):
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>
);
};
我做错了什么?
setLog: Function
不够精确。您需要:
interface Props {
log: string[],
setLog: React.Dispatch<React.SetStateAction<Array<string>>>
};
还有这个
props.setLog(props.log => [...props.log, "Loaded child component."]);
应该是
props.setLog(previousLog => [...previousLog, "Loaded child component."]);
或者,在这种情况下,当该行运行时,它看起来总是在 prop-closure 中具有日志的当前值,因此可以简化为
props.setLog([...props.log, "Loaded child component."]);
我有一个父组件,它定义了一个 useState 挂钩,它是一个字符串数组。然后我有一个需要更新字符串数组的子组件,所以我传递了字符串数组和 useState 的函数来更新它。但是,当我尝试引用 props 数组时,解释器抱怨(参见 code/comments):
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>
);
};
我做错了什么?
setLog: Function
不够精确。您需要:
interface Props {
log: string[],
setLog: React.Dispatch<React.SetStateAction<Array<string>>>
};
还有这个
props.setLog(props.log => [...props.log, "Loaded child component."]);
应该是
props.setLog(previousLog => [...previousLog, "Loaded child component."]);
或者,在这种情况下,当该行运行时,它看起来总是在 prop-closure 中具有日志的当前值,因此可以简化为
props.setLog([...props.log, "Loaded child component."]);