【问题标题】:How does React.useState(<initialState>) update with <initialState> updates?React.useState(<initialState>) 如何随着 <initialState> 更新而更新?
【发布时间】:2021-11-01 20:53:22
【问题描述】:
function Count() {
  const [count, setCount] = React.useState(0)
  const [count2] = React.useState(count)

  return (
    <div>
      <button onClick={() => setCount((prev) => prev + 1)}>+</button>
      <p>count: {count}</p> // does update
      <p>count 2: {count2}</p>. // does not update
    </div>
  )
}

为什么在点击&lt;button&gt;count 更新时count2 不更新?

我认为只有惰性初始化状态(例如 React.useState(() =&gt; count))不会在组件重新渲染时更新。

【问题讨论】:

  • 你没有 count2 的 setter。
  • 因为setCount只针对count1发起。如果您需要更新count2,则需要另一个setState 用于count2:const [count2, setCount2] = React.useState(0)。然后您可以使用setCount2(another_number) 更新count2。初始状态是反应性的。它只是在useState 开头复制的一个值;在那之后,React 不应该重新访问该值,而是依靠 setState 调用来更新该值。
  • useState 如果每次渲染都重新初始化它,那将毫无用处。只有当组件完全从内存中卸载时(例如导航到不同的路线时),然后加载组件的新实例(导航回来时),它才会重新初始化。

标签: reactjs react-hooks use-state


【解决方案1】:

我对你的问题有一个杂乱的解决方案,杂乱无章,可以改进,但到目前为止,我想不出比这更好的解决方案。

  const [count, setCount] = React.useState(0);
  const [count2, setCount2] = React.useState(count);

  const changeStateForCount = () => {
    setCount(count + 1);
    setCount2(count + 1);
  };

  return (
    <div>
      <button onClick={changeStateForCount}>+</button>
      <p>count: {count}</p> {/* does update */}
      <p>count 2: {count2}</p>. {/* does not update */}
    </div>
  );
}

【讨论】:

    【解决方案2】:

    使用依赖于countuseEffect 创建setCount2 以更新count2

    function Count() {
      const [count, setCount] = React.useState(0);
      const [count2, setCount2] = React.useState(count);
    
      useEffect(() => {
        setCount2(count);
      }, [count]);
    
      return (
        <div>
          <button onClick={() => setCount((prev) => prev + 1)}>+</button>
          <p>count: {count}</p> 
          <p>count 2: {count2}</p>
        </div>
      );
    }
    

    【讨论】:

    • 如果它解决了您的问题,请点击绿色对勾标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多