如何显示使用 fetch 调用获取的数据,然后将其设置到数组中,如果满足条件则在 Dom 中显示。目前,我渲染页面的速度比获取数据和处理数据的速度快。
提前致谢
function Profile() {
let myReceipe = [];
const [isPopUp, setPopUp] = useState(false);
ReceipeService.getReceipes().then(data => {
myReceipe = data;
})
const popUpHandler = () => {
setPopUp(!isPopUp);
}
return (
<>
<div className='profile'>
<ProfileHeader/>
<div className='createdposts'>
{myReceipe.length !== 0 ?
<Post popUpHandler={popUpHandler} myReceipe={myReceipe}/>
:
null
}
</div>
</div>
{isPopUp === true ?
<Magnify popUpHandler={popUpHandler}/>
:
null
}
</>
)
}
代码中的几个问题:
useEffect
钩子来发出 HTTP 请求myReceipe
应该处于您的组件的状态数据将始终在组件渲染后加载。
useEffect
钩子正是为此目的而构建的。
从服务器获取数据是一个副作用,所有副作用都属于 useEffect
钩子内。因此,将发出 HTTP 请求的代码移至 useEffect
钩子内。
还要确保
myReceipe
是组件的本地状态
const [myReceipe, setMyReceipe] = useState([]);
当来自服务器的数据可用时,更新状态以触发重新渲染,以便您可以向用户显示数据。
useEffect(() => {
ReceipeService.getReceipes()
.then(data => {
setMyReceipe(data);
});
}, []);
当数据不可用时,向用户显示某种加载微调器,以指示用户数据正在加载。
只需使用状态变量 myReceipe,然后当设置 myReceipe 时,组件将重新渲染,然后在 useEffect 中调用 ReceipeService.getReceipes() :
let myReceipe = [];
const [isPopUp, setPopUp] = useState(false);
const [myReceipe , setmyReceipe ] = useState([]);
useEffect(
()=>{
let isMounted=true;
ReceipeService.getReceipes().then(data => {
// isMounted && insures the component is still mounted
// or else this might through an error if the component has unmounted but the api call responded because you cant just update staet of un unmounted Component
isMounted && setmyReceipe(data);
})
return ()=>{isMounted = false }
},[])
const popUpHandler = () => {
setPopUp(!isPopUp);
}
return (
<>
<div className='profile'>
<ProfileHeader/>
<div className='createdposts'>
{myReceipe.length !== 0 ?
<Post popUpHandler={popUpHandler} myReceipe={myReceipe}/>
:
null
}
</div>
</div>
{isPopUp === true ?
<Magnify popUpHandler={popUpHandler}/>
:
null
}
</>
)
}