I am new to reactJS and am writing code so that before the data is loaded from DB, it will show loading message, and then after it is loaded, render components with the loaded data. To do this, I am using both useState hook and useEffect hook. Here is the code:

问题是,当我检查console.log时,useEffect被触发了两次。因此,代码将两次查询相同的数据,这是应该避免的。

下面是我写的代码:

import React from 'react';
import './App.css';
import {useState,useEffect} from 'react';
import Postspreview from '../components/Postspreview'

const indexarray=[]; //The array to which the fetched data will be pushed

function Home() {
   const [isLoading,setLoad]=useState(true);
   useEffect(()=>{
      /*
      Query logic to query from DB and push to indexarray
      */
          setLoad(false);  // To indicate that the loading is complete
    })
   },[]);
   if (isLoading===true){
       console.log("Loading");
       return <div>This is loading...</div>
   }
   else {
       console.log("Loaded!"); //This is actually logged twice.
       return (
          <div>
             <div className="posts_preview_columns">
             {indexarray.map(indexarray=>
             <Postspreview
                username={indexarray.username}
                idThumbnail={indexarray.profile_thumbnail}
                nickname={indexarray.nickname}
                postThumbnail={indexarray.photolink}
             />
             )}
            </div>
         </div>  
         );
    }
}

export default Home;

有人能帮助我理解为什么它被调用两次,以及如何正确地修复代码吗? 非常感谢!


当前回答

没什么好担心的。当你在开发模式下运行React时。它有时会运行两次。在刺激环境中测试它,您的useEffect将只运行一次。别担心! !

其他回答

将console.log放在useEffect中

可能有其他副作用导致组件重新渲染,但useEffect本身只会被调用一次。您可以通过下面的代码确定地看到这一点。

useEffect(()=>{
      /*
      Query logic
      */
      console.log('i fire once');
},[]);

如果日志“i fire once”被触发不止一次,这意味着您的问题 三件事之一。

该组件在页面中出现多次

这一点应该很明显,您的组件在页面中出现了几次,每一次都将挂载并运行useEffect

树上更高的东西正在卸载和重新安装

组件被强制卸载并在初始渲染时重新安装。这可能是发生在树的更高位置的“关键”更改。你需要使用这个useEffect上升到每一层,直到它只呈现一次。然后你应该能找到原因或重新安装。

反应。开启严格模式

StrictMode将组件呈现两次(在开发中,而不是生产中),以便检测代码中的任何问题并警告您(这可能非常有用)。

这个答案是由@johnhendirx指出的,由@rangfu写的,如果这是你的问题,请给他一些爱。如果您因此而遇到问题,这通常意味着您没有按照预期的目的使用useEffect。在测试文档中有一些很好的信息,你可以在这里阅读

没什么好担心的。当你在开发模式下运行React时。它有时会运行两次。在刺激环境中测试它,您的useEffect将只运行一次。别担心! !

如果你正在使用Next js,将reactStrictMode从“true”更改为false:

将此添加到你的next.config.js中

reactStrictMode: false,

删除<反应。从index.js的StrictMode> 这段代码将是

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

this

root.render(
    <App />
);

React StrictMode在开发服务器上渲染组件两次

新的React文档(目前处于测试阶段)有一个章节精确地描述了这种行为:

如何处理效果发射两次在开发

从文档中可以看出:

通常,答案是实现清理功能。清除函数应该停止或撤消Effect正在做的任何事情。经验法则是,用户不应该能够区分Effect运行一次(如在生产中)和设置→清理→设置序列(如您在开发中看到的)。

所以这个警告应该让你仔细检查你的useEffect,通常意味着你需要实现一个清理函数。