javascript - React setState 仅将最后一项推送到数组
问题描述
我正在使用 ref 从谷歌地图组件中获取一堆标记,在我的主应用程序中,我想将这些标记存储到我所在州的数组中……当我使用 setState 时,它只会推送最后一项……任何想法为什么?
这是我尝试过的
应用组件
state = {
markers: []
};
getMarkerRef = (ref) => {
let newMarkers = [...this.state.markers];
newMarkers.push(ref);
this.setState({ markers: newMarkers });
}
render() {
return (
<div>
<GoogleMap
markerRef={this.getMarkerRef}
/>
</div>
)
}
谷歌地图组件
const newClubList = clubs
.filter(club => club.name.toLowerCase().indexOf(filterTerm.toLowerCase()) >= 0)
.map(club => {
return (
<Marker
key={club.name}
ref={props.markerRef}
/>
)
});
当我在我的 getMarkerRef 函数中控制台日志引用时......我得到了 9 个标记,它们是正确数量的标记......但是,只有最后一个被推送到我的数组中......
我也试过这样做
this.setState({ markers: [...this.state.markers, ref] });
那也没用……
谢谢您的帮助!
解决方案
由于 ref 是一个数组,因此您需要使用 concat 或 spread 语法来更新状态,例如
getMarkerRef = (ref) => {
let newMarkers = [...this.state.markers];
newMarkers = newMarkers.concat(ref);
this.setState({ markers: newMarkers });
}
或者
getMarkerRef = (ref) => {
this.setState(prevState => ({
markers: [...prevState.markers, ...ref]
}));
}
推荐阅读
- javascript - 在数组中获取 indexOf 单击的按钮父级
- python - 我如何循环代码直到用户输入更改python中的变量
- android - 如何使用 CLI 命令检查 Android Gradle 依赖项的更新?
- scrollview - 在 SwiftUI 中,NavigationBarItem 在由嵌入在 List 或 Form 内的 ScrollView 中的 NavigationLink 推送的 View 中不起作用?
- javascript - 在 Webpack4 中设置 ./src 的路径?
- laravel - 为什么我在 Laravel 中得到一个未定义的常量错误?
- javascript - ExpressJs 在 Vanilla jS 上路由和显示页面
- gnuplot - 在 Gnuplot 输出中压缩的图例、标题和轴标签
- excel - 在数据库/Microsoft Access 中创建日期范围
- c# - Thread.Sleep(0) 与 Thread.Sleep(1) 与 Thread.Sleep(2)