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

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

问题描述

我这里有一些简单的代码

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

每次单击按钮时,控制台上都会显示2条日志,指示该组件呈现两次.我发现了一条帖子,说这与严格模式有关,但是我尚未启用严格模式.为什么该组件在每个状态更新时呈现两次?

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?

这是一个 codesandbox 链接进行试用.

Here is a codesandbox link to try it out.

推荐答案

您的App组件在React.StrictMode中呈现,这是导致您的代码在严格模式下运行的原因,并且在严格模式下,控制台显示两次,因为每个功能都是使其在开发模式下运行两次

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

根据反应文档:

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

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:

  • 类组件的构造函数,呈现器和shouldComponentUpdate方法
  • 类组件静态getDerivedStateFromProps方法
  • 功能组件主体
  • 状态更新器功能(setState的第一个参数)
  • 传递给useState,useMemo或useReducer的函数
  • 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天全站免登陆