为什么 useState 会导致组件在每次更新时渲染两次? [英] Why does useState cause the component to render twice on each update?

查看:66
本文介绍了为什么 useState 会导致组件在每次更新时渲染两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有这么简单的代码

import React, { useState } from "react";导入./styles.css";导出默认函数 App() {const [number, setNumber] = useState(0);函数 chaneNumber() {setNumber(state => state + 1);}console.log("这里");返回 (<div className="应用程序"><button onClick={chaneNumber}>更改号码</button>{数字}

);}

每次单击该按钮时,我都会在控制台中收到 2 个日志,表明该组件呈现两次.我发现一个帖子说这是关于严格模式的,但是我没有启用严格模式.为什么这个组件在每次状态更新时渲染两次?

这是一个 codesandbox 试用链接.

解决方案

您的 App 组件在 React.StrictMode 中呈现,这导致您的代码在严格模式下运行,而在严格模式下控制台显示两次,因为每个函数在开发模式下运行两次

ReactDOM.render(<React.StrictMode><应用程序/></React.StrictMode>,根元素);

根据 react 文档:

<块引用>

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

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

I have this simple bit of code here

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

Every time I click the button, I get 2 logs in my console indicating that the component renders twice. I found one post saying this is about strict mode, but I have not enabled strict mode. Why is this component rendering twice on each state update?

Here is a codesandbox link to try it out.

解决方案

Your App component is rendered within React.StrictMode which is what causes your code to run in strict mode and in strict mode the consoles are shown twice because each function is made to run twice in development mode

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);

According to 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

这篇关于为什么 useState 会导致组件在每次更新时渲染两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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