【问题标题】:ReactJS - "setState" with react Hooks, does not merge the state but rather replaces itReactJS - 带有 react Hooks 的“setState”,不合并状态而是替换它
【发布时间】:2020-07-08 08:00:15
【问题描述】:

关于useState 的状态和Websocket 端点流数据,我有以下逻辑。

  const [state, setState] = React.useState({ items: [], activity: [] });

  React.useEffect(() => {
    const currentItems = R.isNil(data.items) ? [] : data.items;
    const currentActivity = R.isNil(data.activity) ? [] : data.activity;

    setState({
      ...state,
      items: Array.from(new Set([...state.items, ...currentItems])),
      activity: Array.from(new Set([...state.activity, ...currentActivity]))
    });
  }, [data]);

  console.log('State:', state); // This just replaces the state instead of merging.

但我无法使状态合并。它只是每次都用流中的新值替换状态。我错过了什么。我没有用那么多钩子,但它看起来很奇怪。 I am spreading the state, then updating, each value。你能告诉我我做错了什么吗?

【问题讨论】:

  • “替换”到底是什么意思?如果您的意思是它们不是同一个对象,那很正常。合并状态应该是一个全新的对象,而不是具有突变的原始对象。也许从控制台添加日志?

标签: javascript reactjs typescript use-state


【解决方案1】:

您可以使用 useState 挂钩中的回调函数来做到这一点:

setState(prev =>{
  ...prev,
  items: Array.from(new Set([...prev.items, ...currentItems])),
  activity: Array.from(new Set([...prev.activity, ...currentActivity]))
});

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 2020-07-04
    • 2021-11-13
    • 2020-01-15
    • 2021-07-20
    • 1970-01-01
    • 2021-11-02
    • 2017-09-05
    相关资源
    最近更新 更多