首页 > 解决方案 > useState() 做双重渲染

问题描述

我在函数组件中使用 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'));

谢谢

标签: reactjsrenderreact-hooks

解决方案


根据反应文档,如果您使用 StrictMode,这是一个有意的功能,可以帮助您检测意外的副作用

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

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

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

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


推荐阅读