【发布时间】:2021-12-02 17:45:24
【问题描述】:
`
- 我有一个点数组(城市、州)
- 我进行 fetch 调用以将我的点转换为(经纬度),因此我将结果推送到数组并尝试设置数组的 setState,但是当我使用 console.log(array) 时,我得到了 []。 `
if (pointsComplete) {
// for (let i = 0; i < pointsComplete.length; i++) {
for await (let x of pointsComplete) {
if (x.city !== "") {
fetch(
`https://singlesearch.alk.com/na/api/search?&query=${x.city} , ${x.state}&maxResults=1`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: trimble_key,
},
}
)
.then((response) => response.json())
.then((data) => {
pointsCoords.push({
Lat: data.Locations[0].Coords.Lat,
Long: data.Locations[0].Coords.Lon,
position: parseInt(x.position),
});
})
.finally(() => {
setPointsCoordsArray(pointsCoords);
});
}
}
}
【问题讨论】:
-
您无法在设置后立即控制台日志并期望看到更新的值。状态值保证在整个渲染周期内保持一致(除非用户突变),您新设置的状态值将在下一次渲染时可用。但是你也在循环中调用
setState,这会产生其他副作用。
标签: javascript arrays reactjs setstate