3 回答
TA贡献1934条经验 获得超2个赞
您不需要像 那样跟踪 API 调用的状态。只需检查轮询是否存在,也可以创建一个新的状态变量来跟踪错误。const [found, setFound] = useState(1)
例如,这将呈现一个带有“加载...”的 div当没有数据时。请参阅下面的代码,了解完整的解决方案,if (!poll) { return <div>Loading...</div>}
import React, { useEffect, useState } from 'react'
import axios from 'axios';
import { Redirect } from 'react-router-dom';
const Poll = (props) => {
const [poll, setPoll] = useState(null);
const [hasError, setHasError] = useState(false);
useEffect(() => {
axios.get(`api/poll/${props.match.params.id}`)
.then(res => {
console.log(res.data);
setPoll(res.data);
})
.catch(err => {
console.log(err.message);
setHasError(true)
});
}, [])
if(!poll) {
console.log('data is still loading')
return(
<div>Loading....</div>
)
}
if (hasError) {
console.log('error when fetching data');
return (
<Redirect to="/" push />
)
}
return (
<div>
{
poll && <div>/* The JSX you want to display for the poll*/</div>
}
</div>
);
}
export default Poll
TA贡献1866条经验 获得超5个赞
在您的 than 中,尝试使用过滤器:
setPoll(poll.filter(poll => poll.id !== id));
确保用您的识别器替换 id
TA贡献1852条经验 获得超7个赞
标准方法是为加载和错误状态设置其他变量,如下所示
const Poll = (props) => {
const [poll, setPoll] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
setLoading(true);
axios.get(`api/poll/${props.match.params.id}`)
.then(res => {
console.log(res.data);
setPoll(res.data);
})
.catch(err => {
console.log(err.message);
setError(true);
})
.finally(()=> {
setLoading(false);
};
}, [])
if(error) return <span>error<span/>
if(loading) return <span>loading<span/>
return (
<div>
// your poll data
</div>
)
}
添加回答
举报