首页 > 解决方案 > 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] });

那也没用……

谢谢您的帮助!

标签: javascriptreactjs

解决方案


由于 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]
     }));
}

推荐阅读