useState() 做双重渲染 [英] useState() do double render

查看:34
本文介绍了useState() 做双重渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数组件中使用 useState() 并且第一次渲染调用了两次.它是正确的还是错误的?如果正确,为什么要渲染两次?setCount 也渲染组件两次.

function Example() {const [count, setCount] = useState(0);console.log("渲染");返回 (<div><p>您点击了 {count} 次</p><button onClick={() =>setCount(count + 1)}>点击我

);}ReactDOM.render(, document.getElementById('uu5'));

谢谢

解决方案

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

<块引用>

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

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

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

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

I'm using useState() in function component and first render is calling twice. Is it correct or mistake? If it is correct why does it render twice? setCount renders the component twice too.

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'));

Thanks

解决方案

According to react docs, it's an intentional feature to help you to detect unexpected side effects if you're using StrictMode

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

Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.

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

这篇关于useState() 做双重渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆