我写了简单的代码如下
import React, { useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(1);
useEffect(() => {
setCount(2);
}, [count]);
console.info("render: ", count);
return <div>{count}</div>;
}
控制台输出为
render: 1
render: 2
render: 2
为什么“render:2”输出两次
最佳答案
问题在于您无条件更新用作依赖项的状态。
此行为并不意外。
参见Bailing out of a state update
If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)
Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with
useMemo
.
在初始渲染(即第一个日志)时,count
为 1。
useEffect
Hook 运行并将状态更新排入队列,然后处理更新。
下一次渲染(第二个日志)时,计数
为 2。
count
状态值已更新,因此 useEffect
Hook 回调运行并将另一个状态更新排入同一值,然后处理该更新。
在下一次渲染(即第三个日志)时,count
仍为 2。
count
状态尚未更改,因此不会触发 useEffect
Hook 回调。
关于reactjs - 在效果中 setState 之后 React 功能组件渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71554217/