本文介绍了React Hooks:即使使用空数组作为参数,useEffect() 也会被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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

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

下面是我写的代码:

从'react'导入React;导入'./App.css';从反应"导入 {useState,useEffect};从../components/Postspreview"导入 Postspreviewconst indexarray=[];//获取的数据将被推送到的数组函数主页(){const [isLoading,setLoad]=useState(true);useEffect(()=>{/*从数据库查询并推送到索引数组的查询逻辑*/设置负载(假);//表示加载完成})},[]);如果(isLoading===true){console.log("加载中");return <div>这是加载...</div>}别的 {console.log("加载完毕!");//这实际上记录了两次.返回 (<div><div className="posts_preview_columns">{indexarray.map(indexarray=><帖子预览用户名={indexarray.username}idThumbnail={indexarray.profile_thumbnail}昵称={indexarray.nickname}postThumbnail={indexarray.photolink}/>)}

);}}导出默认首页;

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

解决方案

将console.log放在useEffect里面

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

useEffect(()=>{/*查询逻辑*/console.log('我触发一次');},[]);

如果日志i fire once"被多次触发,这意味着您的问题是两件事之一.

此组件在您的页面中多次出现

这个应该很明显,你的组件在页面中出现了几次,每个都会挂载并运行 useEffect

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

组件在其初始渲染时被迫卸载并重新安装.这可能是类似于钥匙"的东西.变化发生在树的更高处.您需要使用此 useEffect 提升每个级别,直到它仅呈现一次.那么你应该能够找到原因或重新安装.


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:

The problem is, useEffect is triggered twice when I check with console.log. The code is thus querying the same data twice, which should be avoided.

Below is the code that I wrote:

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;

Can someone help me out in understanding why it is called twice, and how to fix the code properly?Thank you very much!

解决方案

Put the console.log inside the useEffect

Probably you have other side effects that cause the component to rerender but the useEffect itself will only be called once. You can see this for sure with the following code.

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

If the log "i fire once" is triggered more than once it means your issue isone of 2 things.

This component appears more than once in your page

This one should be obvious, your component is in the page a couple of times and each one will mount and run the useEffect

Something higher up the tree is unmounting and remounting

The component is being forced to unmount and remount on its initial render. This could be something like a "key" change happening higher up the tree. you need to go up each level with this useEffect until it renders only once. then you should be able to find the cause or the remount.

这篇关于React Hooks:即使使用空数组作为参数,useEffect() 也会被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:54