代码之家  ›  专栏  ›  技术社区  ›  CCCC

React-依赖于另一个状态的状态值无法更新

  •  0
  • CCCC  · 技术社区  · 3 年前

    复制步骤

    1. 进入Codesandbox控制台后,您可以看到 typeA 和 allTypes 。
      enter image description here
    2. 点击“更新类型A”按钮
    3. 在控制台中,您可以看到的更新值 A类 和 所有类型 。
      enter image description here

    预期行为
    在里面 所有类型 ,字段的值 A类 应该是 "different value" 。

    实际行为
    字段的值 A类 仍然保持不变。

    问题

    1. 为什么字段的值 A类 使现代化
    2. 如何修复?

    应用程序.js

    import "./styles.css";
    import { useState, useEffect } from "react";
    
    export default function App() {
      const [typeA, setTypeA] = useState("01");
      const [typeB, setTypeB] = useState("abc");
    
      const [allTypes, setAllTypes] = useState({
        typeA: [typeA],
        typeB
      });
      console.log({ typeA }); // updated successfully
      console.log({ allTypes }); // the value of typeA remain unchanged
      return (
        <div>
          <button
            onClick={() => {
              setTypeA("different value");
            }}
          >
            Update type A
          </button>
        </div>
      );
    }
    

    代码沙盒
    https://codesandbox.io/s/jovial-lichterman-w1kbph?file=/src/App.js

    1 回复  |  直到 3 年前
        1
  •  2
  •   Nathanael    3 年前

    useState的参数是一个初始值设定项,它不会在初始呈现之后更新。你可以 useMemo 以实现您的预期行为。不能将值“输入”到useState的参数中。

    const [typeA, setTypeA] = useState("01");
    const [typeB, setTypeB] = useState("abc");
    
    const allTypes = useMemo(() => {
       return {typeA: [typeA], typeB}
    },[typeA, typeB])
    

    您也可以在不使用Memo的情况下执行此操作,但每次渲染时都会重新创建对象引用。