我正在编写代码,以便在从数据库加载数据之前显示加载消息,然后在加载完成后使用加载的数据渲染组件。为了实现这一点,我同时使用了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;
为什么它被调用了两次,以及如何正确修复代码?