【问题标题】:Updating properties of an object in React with useState使用 useState 在 React 中更新对象的属性
【发布时间】:2021-01-22 04:12:52
【问题描述】:

我有这个状态:

  const [test, setTest] = useState({
    test1: "test",
    test2: "test",
    test3: "test",
  });

useEffect(() => {
    setTimeout(() => {
      setTest({
        ...test,
        test1: "test1",
      });
    }, 2000);

    setTimeout(() => {
      setTest({
        ...test,
        test2: "test2",
      });
    }, 3000);
  }, []);

我想得到类似的东西:

{
  test1: "test1"
  test2: "test2"
  test3: "test"
}

但我明白了:

{
  test1: "test"
  test2: "test2"
  test3: "test"
}

这可能吗? 我做错了什么?谢谢

我需要保留这个对象形式,我正在使用 API,我不希望每个 API 有 30 个不同的 useState。我只想在一个对象中获取所有 API 数据并将其用作道具。

【问题讨论】:

    标签: reactjs state javascript-objects use-state


    【解决方案1】:

    改为使用回调,这样您就拥有对当前状态 test 的最新引用,而不是仅引用初始挂载时的原始(未修改)test

    setTest(test => ({
        ...test,
        test2: "test2",
    }));
    

    【讨论】:

      猜你喜欢
      • 2020-07-16
      • 1970-01-01
      • 2020-03-29
      • 2020-08-31
      • 2022-09-27
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多