reactjs - react 钩子(Hook) : useEffect() is called twice even if an empty array is used as an argument

标签 reactjs react-hooks

我是 reactJS 的新手并且正在编写代码,以便在从 DB 加载数据之前,它会显示加载消息,然后在加载之后,使用加载的数据渲染组件。为此,我同时使用了 useState 钩子(Hook)和 useEffect 钩子(Hook)。这是代码:

问题是,当我检查 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;

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

最佳答案

将 console.log 放在 useEffect 中
可能您还有其他副作用会导致组件重新呈现,但 useEffect 本身只会被调用一次。您可以使用以下代码肯定地看到这一点。

useEffect(()=>{
      /*
      Query logic
      */
      console.log('i fire once');
},[]);
如果日志“我触发一次”被多次触发,则意味着您的问题是
三件事之一。
此组件在您的页面中出现多次
这应该很明显,您的组件在页面中出现了几次,每个都将安装并运行 useEffect
树上更高的东西正在卸载和重新安装
该组件被强制卸载并在其初始渲染时重新安装。这可能类似于在树的更高处发生的“关键”变化。您需要使用此 useEffect 升级每个级别,直到它只渲染一次。那么您应该能够找到原因或重新安装。
React.Strict 模式开启

StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).


这个答案由@johnhendirx 指出并由@rangfu 撰写,见link如果这是你的问题,请给他一些爱。

关于reactjs - react 钩子(Hook) : useEffect() is called twice even if an empty array is used as an argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60618844/

相关文章:

javascript - 将 Material UI Typography 更改为样式组件

reactjs - Redux 工具包根据 api 响应更新状态

javascript - 如何防止 Element.focus() 在 contenteditable div 中更改光标位置?

reactjs - 如何更新 React-Hooks Apollo 轮询中的变量?

reactjs - 钩子(Hook)和不可变状态

javascript - 功能 react 如何不重置状态?

javascript - 在 React 中重新渲染 moment.fromNow()

javascript - 在 React 功能组件中多次调用函数

javascript - 如何使用 react-query 将来自不同 react-query Hook 的数据同步连接在一起?

reactjs - react 钩子(Hook)中的prevstate