[英]React cannot update state
我不知道為什么我不能更新我的狀態(請參閱 setCoords)。 請求返回一個 200 代碼,我試圖檢索的元素存在:
這是我的代碼:
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));
}
}
謝謝你的幫助!
嘗試使用回調
...
const onSearch = useCallback(async () {
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));
}
}, [coords]);
...
參考: https : //reactjs.org/docs/hooks-reference.html#usecallback
需要注意的一件事是,不要將await
與then
混合(更多相關信息: 可以將 await 然后混合在一個實現中嗎? )。 由於您使用的是async
,我建議您將 all 更改為await
,如下所示
另一件要注意的事情是setStates
調用(即setCoords
和setForecast
和setCity
)本質上是異步的,這意味着設置狀態后的即時console.log
不會記錄剛剛更新的值。 相反,React 會將這些 setState 安排到下一次渲染 - 因此,您只能在下一個渲染周期中查看/訪問最新更新的值。 如果要記錄值,可以將它們放在 HTML 中的<pre>
標記中,或者在開頭執行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>
setState()操作在 React 中是異步的。 所有這一切都意味着您不能依賴在 setState 中應用的新狀態值立即應用。 與 setState 一樣, fetch()本質上也是異步的。因此,console.log 語句不會等待 setState() 或 fetch() 執行。 在這種情況下,您始終可以通過 setState() 的回調參數來處理它。
await apiGet(`/geo/1.0/direct?q=${city}`)
.then(r => r.json())
.then(r => setCoords(data => {lat: r[0].lat, lon:r[0].lon}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.