React setState only pushing last item to array

时间:2018-07-25 04:53:25

标签: javascript reactjs

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?

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

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...

I have also tried doing it this way

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

That didn't work either...

Thanks for the help!

1 个答案:

答案 0 :(得分:1)

Since ref is an array, you need to either use concat or spread syntax to update the state like

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