useState() 做双重渲染

Ond*_*pek 7 render reactjs react-hooks

我在函数组件中使用 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'));
Run Code Online (Sandbox Code Playgroud)

谢谢

小智 11

根据 react docs,这是一个有意的功能,可帮助您在使用 StrictMode 时检测意外的副作用

严格模式无法自动为您检测副作用,但它可以通过使它们更具确定性来帮助您发现它们。这是通过有意重复调用以下函数来完成的:

  • 类组件构造函数、render 和 shouldComponentUpdate 方法
  • 类组件静态 getDerivedStateFromProps 方法
  • 函数组件体
  • 状态更新器函数(setState 的第一个参数)
  • 传递给 useState、useMemo 或 useReducer 的函数

注意:这仅适用于开发模式。生命周期不会在生产模式下被双重调用。

https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects