【发布时间】: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>
)
}
为什么在点击<button> 后count 更新时count2 不更新?
我认为只有惰性初始化状态(例如 React.useState(() => 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