useState()进行双重渲染

时间:2019-02-28 14:10:58

标签: reactjs render react-hooks

我在函数组件中使用useState(),并且第一个render调用了两次。是正确还是错误?如果正确,为什么会渲染两次? 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'));

谢谢

3 个答案:

答案 0 :(得分:9)

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

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

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

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

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

答案 1 :(得分:1)

在index.js文件中删除包装器

答案 2 :(得分:0)

问题在React DevTools中。关闭控制台后,组件仅呈现一次。但是,如果您打开React DevTools并重新加载页面,渲染将显示两次。打开example并尝试。 (反应16.8.3)

相关问题