我遇到一个问题,在设置状态和消息更改之前,空消息(I dont have Partners
(会闪烁一秒钟左右。。有没有办法在一切解决之前不表现出来?
const Dashboard = () => {
const [partners, setPartners] = useState([]);
useEffect(() => {
async function getPartners() {
await axios.get('/api/partners').then(response => {
setPartners(response.data.data);
})
}
getPartners();
}, []);
return (
<>
{partners?.length ? <div><p>I have Partners</p></div> : <div><p>I dont have Partners</p></div>}
</>
)
}
export default Dashboard;
有几种方法可以实现这一点,最简单的方法是使用另一种状态来指示HTTP请求状态。以下是如何实现的。
const Dashboard = () => {
const [partners, setPartners] = useState([]);
const [status, setStatus] = useState('idle');
useEffect(() => {
setStatus('pending');
async function getPartners() {
await axios.get('/api/partners').then(response => {
setPartners(response.data.data);
setStatus('resolved');
})
}
getPartners();
}, []);
return (
<>
{status === 'idle' || status === 'pending' ?
<LoadingComponent /> // A custom component to represent loading status
:
<>
{partners?.length ? <div><p>I have Partners</p></div> : <div><p>I dont have Partners</p></div>}
<>
}
</>
)
}
export default Dashboard;