useState() 做双重渲染
useState() do double render
我在函数组件中使用 useState() 并且第一次渲染调用了两次。是对还是错?如果它是正确的,为什么它会渲染两次? setCount 也会渲染组件两次。
function Example() {
const [count, setCount] = useState(0);
console.log("render");
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('uu5'));
谢谢
问题出在 React DevTools 中。当控制台关闭时,组件只渲染一次。但是如果你打开 React DevTools 并重新加载页面,渲染将显示两次。打开 example 并尝试。 (反应 16.8.3)
根据 React 文档,如果您使用 StrictMode,这是一项有意的功能,可帮助您检测意外的副作用
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
- Class component constructor, render, and shouldComponentUpdate
methods
- Class component static getDerivedStateFromProps method
- Function component bodies
- State updater functions (the first argument
to setState)
- Functions passed to useState, useMemo, or useReducer
Note:
This only applies to development mode. Lifecycles will not be double-invoked in production mode.
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
删除 index.js 文件中的 包装器
我在函数组件中使用 useState() 并且第一次渲染调用了两次。是对还是错?如果它是正确的,为什么它会渲染两次? setCount 也会渲染组件两次。
function Example() {
const [count, setCount] = useState(0);
console.log("render");
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('uu5'));
谢谢
问题出在 React DevTools 中。当控制台关闭时,组件只渲染一次。但是如果你打开 React DevTools 并重新加载页面,渲染将显示两次。打开 example 并尝试。 (反应 16.8.3)
根据 React 文档,如果您使用 StrictMode,这是一项有意的功能,可帮助您检测意外的副作用
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
- Class component constructor, render, and shouldComponentUpdate methods
- Class component static getDerivedStateFromProps method
- Function component bodies
- State updater functions (the first argument to setState)
- Functions passed to useState, useMemo, or useReducer
Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
删除 index.js 文件中的