我正在编写代码,以便在从数据库加载数据之前,它将显示加载消息,然后在加载后,使用加载的数据渲染组件。为此,我同时使用 useState 挂钩和 useEffect 挂钩。这是代码:
问题是,当我检查 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 会渲染组件两次(在开发中,而不是在生产中),以便检测代码中的任何问题并向您发出警告(这可能非常有用)。
这个答案是由@johnhendirx指出并由@rangfu撰写的,请参阅link如果这是你的问题,请给他一些爱。如果您因此遇到问题,通常意味着您没有将 useEffect 用于其预期目的。您可以在文档中阅读有关此内容的一些重要信息here
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)