I can't figure why I can't update my state (see setCoords). The request returns with a 200 code and the elements I'm trying to retrieve exists : ![enter image description here](https://i.stack.imgur.com/a8QzN.png)
这是我的代码:
const App = () => {
const [city, setCity] = useState("");
const [forecast, setForecast] = useState(null);
const [coords, setCoords] = useState({});
const handleSearchChange = ev => {
setCity(ev.target.value);
};
async function onSearch() {
if (city) {
await apiGet(`/geo/1.0/direct?q=${city}`)
.then(r => r.json())
.then(r => setCoords({lat: r[0].lat, lon:r[0].lon})); // doesn't't set anything
await console.log(coords) // console logs {}
await apiGet(
`/data/2.5/onecall?lat=${coords.lat}&lon=${coords.lon}&exclude=current,minutely,hourly,alerts`
)
.then(r => r.json())
.then(r => setForecast(r));
}
}
感谢您的帮助!
需要注意的一件事是不要混合await
with then
(更多相关内容:可以先等待然后混合在一个实现中吗? https://stackoverflow.com/questions/54574662/can-await-and-then-be-mixed-in-one-implementation)。既然你正在使用async
,我建议你全部更改为await
,如下所示
另一件需要注意的事情是setStates
调用(即setCoords
and setForecast
and setCity
) is 异步本质上,这意味着立即console.log
设置状态后将not记录刚刚更新的值。相反,React 会将这些 setState 安排到下一个渲染 - 因此,您只能在下一个渲染周期中查看/访问最新的值。如果您想记录值,可以将它们放在<pre>
HTML 中的标记,或者执行console.log
一开始,如下所示:
const App = () => {
const [city, setCity] = useState("");
const [forecast, setForecast] = useState(null);
const [coords, setCoords] = useState({});
console.log("City", city, "Forecast", forecast, "Coords", coords);
const handleSearchChange = ev => {
setCity(ev.target.value);
};
async function onSearch() {
if (city) {
const resNonJson = await apiGet(`/geo/1.0/direct?q=${city}`)
const resJson = await resNonJson.json())
const item = resJson[0];
setCoords({lat: item.lat, lon: item.lon}));
// Note that `setState` is async so console.log will not get the just-updated value
console.log(coords) // {}
console.log(item) // {lat:..., lon:...}
const resNonJson2 = await apiGet(
`/data/2.5/onecall?lat=${item.lat}&lon=${item.lon}&exclude=current,minutely,hourly,alerts`
)
const resJson2 = await resNonJson2.json())
setForecast(resJson2);
}
}
... (other codes that I trust you do correctly)
return <div>
<pre>{JSON.stringify(coords)}</pre>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)