我从套接字监听数据。当我收到数据时,我像这样更新数组。但是状态没有更新。请帮助我并提前致谢
socket?.on('addLocation', data => {
console.log('addLocation', data);
let isFound = false;
let newMarkers = markers.map(marker => {
if (marker.fleet_id == data.fleetId) {
isFound = false;
return {
...marker,
latitude: data.lat,
longitude: data.long,
};
} else {
return marker;
}
});
if (!isFound) {
newMarkers = [
...newMarkers,
{
fleet_id: data.fleetId,
latitude: data.lat,
longitude: data.long,
},
];
}
setMarker(newMarkers);
})
socket?.on('addLocation', data => {
console.log('addLocation', data);
let isFound = false;
let newMarkers = markers.map(marker => {
if (marker.fleet_id == data.fleetId) {
isFound = false;
return {
...marker,
latitude: data.lat,
longitude: data.long,
};
} else {
return marker;
}
});
if (!isFound) {
newMarkers = [
...newMarkers,
{
fleet_id: data.fleetId,
latitude: data.lat,
longitude: data.long,
},
];
}
setMarker(newMarkers);
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设
markers
的状态是setMarker
正在更新,那么这似乎是markers
状态上的陈旧封装问题。回调正在更新关闭状态,而不是当前的标记状态值。使用功能状态更新来正确访问以前的状态而不是过时的值。
Array.prototype.map
旨在将一组值映射到另一组值,并且不应该产生像设置isFound
标志这样的副作用。首先搜索数据以确定是否需要更新状态或是否需要附加新元素。例子:
Assuming
markers
the state thatsetMarker
is updating then this appears to be an issue of a stale enclosure over themarkers
state. The callback is updating the closed over state and not the currentmarkers
state value.Use a functional state update to correctly access the previous state instead of the stale value.
Array.prototype.map
is meant to map one set of values to another, and shouldn't have side-effects like setting anisFound
flag. Search the data first to decide if the state needs to be updated or if a new element needs to be appended.Example:
这里有一些事情:
setMarkers
的回调风格来确保您在修改时拥有“最新”副本。isFound
永远是 false 也是一个逻辑问题。There are a few things here:
setMarkers
to ensure you have the "latest" copy when you're modifying it.isFound
will always be false is also a logic issue.