猿问

为什么一个简单的 React 组件会渲染两次?

我刚刚启动了一个新的 create-react-app 项目,并注意到 React 渲染了两次组件!我在package.json中的反应版本是"react": "^16.13.1"


import React, { useRef } from "react";


const App = () => {

  const renders = useRef(0);

  console.log("renders: ", renders.current++);


  return (

    <div>

      Hello

    </div>

  );

};

这在第一次渲染时产生:


renders: 0

renders: 0

现在,如果我添加一个按钮来增加状态,每个状态变化也会产生两个额外的渲染:


import React, { useRef } from "react";


const App = () => {

  const [count, setCount] = useState(0);

  const renders = useRef(0);

  console.log("renders: ", renders.current++);


  return (

    <div>

      <button onClick={() => setCount(count + 1)}>increment</button>

      <div>count: {count}</div>

    </div>

  );

};

这将导致:


//--- initial render

renders: 0

renders: 0

//--- first click

renders: 1

renders: 2

//--- second click

renders: 3

renders: 4

//--- third click

renders: 5

renders: 6

这是正常现象还是最新版本的 React 中的错误?


繁星淼淼
浏览 195回答 2
2回答

隔江千里

好的,看来我找到了原因。检查后index.js我发现以下内容:ReactDOM.render(&nbsp; <React.StrictMode>&nbsp; &nbsp; <App />&nbsp; </React.StrictMode>,&nbsp; document.getElementById('root'));看起来 create-react-app 现在包括React.StrictMode在开发模式(而不是生产模式)中双重调用某些方法。

呼如林

除了您发现的 StrictMode 问题之外,我认为当您使用ref类似的东西时它会产生副作用,因此您通常需要将其放入useEffect以防止它渲染两次:import React, { useState, useEffect, useRef } from "react";const App = () => {&nbsp; const [count, setCount] = useState(0);&nbsp; const renders = useRef(0);&nbsp; useEffect(() => {&nbsp; &nbsp; // Every time the component has been re-rendered,&nbsp; &nbsp; // the counter is incremented&nbsp; &nbsp; console.log("renders: ", renders.current++);&nbsp; });&nbsp;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <button onClick={() => setCount(count + 1)}>increment</button>&nbsp; &nbsp; &nbsp; <div>count: {count}</div>&nbsp; &nbsp; </div>&nbsp; );};export default App;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答