简体   繁体   English

反应setState仅将最后一项推入数组

[英]React setState only pushing last item to array

I'm getting a bunch of markers from a google maps component using ref and in my main app I want to store those markers into an array in my state...when I use setState it only pushes the last item...any ideas on why? 我正在使用ref从Google Maps组件中获取一堆标记,在我的主应用程序中,我想将这些标记存储到状态下的数组中。当我使用setState时,它只会推送最后一项...任何想法为什么?

Here's what I tried 这是我尝试过的

App component 应用程序组件

state = {
  markers: []
};

getMarkerRef = (ref) => {
  let newMarkers = [...this.state.markers];
  newMarkers.push(ref);
  this.setState({ markers: newMarkers });
}

render() {
 return (
   <div>
     <GoogleMap
       markerRef={this.getMarkerRef}
     />
    </div> 
 )
}

The GoogleMap component GoogleMap组件

const newClubList = clubs
  .filter(club => club.name.toLowerCase().indexOf(filterTerm.toLowerCase()) >= 0)
  .map(club => {
    return (
      <Marker
        key={club.name}
        ref={props.markerRef}
      />
      )
    });

When I console log ref inside my getMarkerRef function...I get back 9 markers which are the correct number of markers... however, only the last one is pushed to my array... 当我在getMarkerRef函数中控制台记录ref时...我得到9个标记,这些标记是正确数量的标记...但是,只有最后一个标记被推送到我的数组中...

I have also tried doing it this way 我也尝试过这样做

this.setState({ markers: [...this.state.markers, ref] });

That didn't work either... 那也不起作用...

Thanks for the help! 谢谢您的帮助!

Since ref is an array, you need to either use concat or spread syntax to update the state like 由于ref是一个数组,因此您需要使用concat或spread语法来更新状态,例如

getMarkerRef = (ref) => {
 let newMarkers = [...this.state.markers];
 newMarkers = newMarkers.concat(ref);
 this.setState({ markers: newMarkers });
}

or 要么

getMarkerRef = (ref) => {
    this.setState(prevState => ({ 
         markers: [...prevState.markers, ...ref]
     }));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM