我这里有一段简单的代码
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [number, setNumber] = useState(0);
function chaneNumber() {
setNumber(state => state + 1);
}
console.log("here");
return (
<div className="App">
<button onClick={chaneNumber}>Change number</button>
{number}
</div>
);
}
每次单击该按钮时,我都会在控制台中收到 2 个日志,表明该组件渲染了两次。我找到了一个post说这是关于严格模式的,但我还没有启用严格模式。为什么这个组件在每次状态更新时渲染两次?
这是一个codesandbox链接来尝试一下。
最佳答案
您的应用程序组件在 React.StrictMode
中呈现,这导致您的代码在严格模式下运行,在严格模式下,控制台显示两次,因为每个函数在开发模式下运行两次
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
根据react docs :
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
关于javascript - 为什么 useState 会导致组件在每次更新时渲染两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61578158/