javascript - 在 React typescript 中的 useState 钩子(Hook)中使用 PrevState

标签 javascript reactjs typescript use-state

我只是想弄清楚如何在 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);

setCount(c => c + 1) is better than setCount(count + 1)

关于javascript - 在 React typescript 中的 useState 钩子(Hook)中使用 PrevState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69453230/

相关文章:

typescript - .ts 文件不被视为 TypeScript 模块

javascript - 为什么添加新 block 后折叠/展开不起作用?

javascript - 如何从 Node JS 中的 url 下载文件?

javascript - jQuery Datepicker onSelect 事件获取类

javascript - React SDK可以在纯JavaScript中使用吗?

node.js - 在终端中使用 tsc 编译类型脚本时出现类型脚本错误

javascript - 使用 click() 函数打开链接但保持当前窗口的焦点

reactjs - React.cloneElement 克隆已经克隆的元素以添加新的 Prop

reactjs - react : Function components cannot be given refs when displaying a modal

angular 2 typescript 无法在环境上下文中声明实现