我只是想弄清楚如何在 React typescript 的 useState Hook 中使用 prevState
。该按钮使用 objectData 中的数据进行映射。
到目前为止我已经:
let data = dataFromFile;
const [chart, setChart] = React.useState<ChartInterface[]>(data);
在我正在做的组件中:
export interface ActiveObject {
id: number;
title: string;
cb: (idx: number) => void;
};
export interface ButtonGroupState {
activeObject: ActiveObject | null;
objects: ActiveObject[];
};
export interface ButtonGroupProps {
data: Array<ActiveObject>
}
const ObjectData: ActiveObject[] = [
{
id: 1,
title: "1 way day",
cb: () => { setChart(prevState => prevState.set(Data7Day)) }
},
];
但这并没有真正起作用,有什么想法吗?我得到属性“set”在类型“ChartInterface[]”上不存在。我知道这与接口(interface)有关,但是这是在 useState 中使用 PrevState 的方法吗?是否需要它?
最佳答案
根据docs :
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here’s an example of a counter component that uses both forms of setState:
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
所以,基本上这意味着您还可以将函数传递给 setter function returned by the useState Hook .
当您需要在当前状态的基础上设置下一个状态时,您需要将参数作为函数传递。正如 @RameshReddy 指出的,如果 cb 函数应该将图表数组更改为名为 Data7Day
的新数组,不需要使用功能状态更新,可以直接调用setChart(Data7Day)
例如...
const [count, setCount] = useState(0);
关于javascript - 在 React typescript 中的 useState 钩子(Hook)中使用 PrevState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69453230/