当重新加载页面时,我得到状态未定义错误



第一次一切都很好,但在刷新页面时出现错误和未定义状态如果我注释h1和p标签并取消注释,那么错误就会解决并再次出现。我刷新

这是我的代码

import { useState, useEffect } from "react";
function App() {
var [state, setState] = useState({});
useEffect(() => {
fetch(
"https://api.openweathermap.org/data/2.5/find?q=kolkata&units=metric&appid=907c99e1a96b5d38487d8d9c19b413fc"
)
.then((doc) => {
return doc.json();
})
.then((doc) => {
setState(doc);
});
}, []);
return (
<div className="App">
<div className="welcome">
<h1>
{state.list[0].main.temp}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0].main.feels_like}</p>
<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
</div>
);
}
export default App;

您的状态是一个空对象。最初,您必须进行检查,就像我在下面所做的那样。

import { useState, useEffect } from "react";
function App() {
var [state, setState] = useState({});
useEffect(() => {
fetch(
"https://api.openweathermap.org/data/2.5/find?q=kolkata&units=metric&appid=907c99e1a96b5d38487d8d9c19b413fc"
)
.then((doc) => {
return doc.json();
})
.then((doc) => {
setState(doc);
});
}, []);
return (
<div className="App">
<div className="welcome">
{Object.keys(state).length>0?<><h1>
{state.list[0].main.temp}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0].main.feels_like}</p></>:""}

<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
</div>
);
}
export default App;

或者如果您想避免Object.keys,则将默认状态设为null

import { useState, useEffect } from "react";

function App() {
var [state, setState] = useState(null);

useEffect(() => {
fetch(
"https://api.openweathermap.org/data/2.5/find?q=kolkata&units=metric&appid=907c99e1a96b5d38487d8d9c19b413fc"
)
.then((doc) => {
return doc.json();
})
.then((doc) => {
setState(doc);
});
}, []);

return (
<div className="App">
<div className="welcome">
{state?<><h1>
{state.list[0].main.temp}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0].main.feels_like}</p></>:""}

<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
</div>
);
}

export default App;

UseEffect是在组件第一次完全渲染时调用的,所以当您使用state.list[0].main.attribute时,您调用的是未定义的,因为您的初始状态是{}。试试这个:

<div className="welcome">
<h1>
{state.list[0] ? state.list[0].main.temp : ""}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0] ? state.list[0].main.feels_like : ""}</p>
<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>

相关内容

最新更新