为什么我的组件渲染两次?
export default function App() {
console.log("asd");
const [count, setCount] = useState(0);
return (
<div>
<Title count={count} />
<button
onClick={() => {
setCount(count + 1);
}}
/>
</div>
);
}
//console= "asd" "asd"
它渲染了两次,但是如果我删除 useState 它就不会发生
最佳答案
您的应用程序可能由 React.StrictMode 包装。 StrictMode 是一个用于突出显示应用程序中潜在问题的工具。
StrictMode 目前可帮助:
Identifying components with unsafe lifecycles
Warning about legacy string ref API usage
Warning about deprecated findDOMNode usage
Detecting unexpected side effects
Detecting legacy context API
严格模式无法自动为您检测副作用,但它可以通过使副作用更具确定性来帮助您发现它们。这是通过有意双重调用以下函数来完成的:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies (your app is functional component)
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
关于reactjs - 使用 hooks 进行两次 React 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61549481/