每次刷新页面时都会出现React api属性错误



我是React的新手,我正在从新冠肺炎api获取数据,第一次渲染时页面中没有错误,但刷新页面后出现错误。我使用了useEffect hoook并传递了一个空数组作为参数。

useEffect(()=>{
axios.all([
axios.get('https://disease.sh/v3/covid-19/historical/all?lastdays=all'),
axios.get('https://disease.sh/v3/covid-19/continents'),

])
.then(function(response) {
setCovid(response[0].data);
setContinent(response[1].data);


}).catch((err)=>console.log(err));
},[])

我定义的状态是:

const [covid,setCovid]=useState([]);
const [continent,setContinent]=useState([]);

axios.get('https://disease.sh/v3/covid-19/continents')提取的数据的形式为

[
{
"updated": 1607090269045,
"cases": 16896655,
"todayCases": 16922,
"deaths": 420577,
"todayDeaths": 718,
"recovered": 10332765,
"todayRecovered": 12336,
"active": 6143313,
"critical": 30951,
"casesPerOneMillion": 28586.82,
"deathsPerOneMillion": 711.56,
"tests": 221877339,
"testsPerOneMillion": 375386.05,
"population": 591064426,
"continent": "North America",
"activePerOneMillion": 10393.64,
"recoveredPerOneMillion": 17481.62,
"criticalPerOneMillion": 52.36,
"continentInfo": {
"lat": 31.6768272,
"long": -146.4707474
},
"countries": [
...

大陆是其中一个价值观。

除此之外,我已经宣布

console.log(continent[0].continent);

对于第一次渲染,它工作得很好,但当我刷新页面时,我会得到一个错误

TypeError: Cannot read property 'continent' of undefined

此外,对于第一个渲染,即使我在useEffect中传递了空数组作为参数,控制台也会显示6个输出,我如何使其仅为一个渲染?

请帮我纠正这两个错误,谢谢:(

不要在useFfect之外控制台日志,它肯定会给您一个错误。由于Axios需要时间来解决请求并返回数据,因此在这段时间内,continent状态的值将保持为[],这就是该错误的原因。

相反,Axios返回内部结果后的控制台日志,然后阻止

useEffect(()=>{
axios.all([
axios.get('https://disease.sh/v3/covid-19/historical/all?lastdays=all'),
axios.get('https://disease.sh/v3/covid-19/continents'),

])
.then(function(response) {
setCovid(response[0].data);
setContinent(response[1].data);
console.log(continent[0].continent);
}).catch((err)=>console.log(err));
},[])

在未来,如果你想避免这个错误,那么为了更安全起见,使用如下所示的零传播算子:

console.log(continent[0]?.continent);

最新更新