简体   繁体   中英

How to lift state up in React from a response with Axios?

I have a parent App.js component with state and a child MapContainer.js also with state . The child component displays a google map and I'm using the following function to lift state up from child to parent:

mapClicked = (event) => {
     const { markers } = this.state;
     let url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+ event.latLng.lat() + ',' + event.latLng.lng()+ '&key='+ 'MYGOOGLEAPIKEY' +'';
     axios.get(url).then(response => this.setState({
       googleReverseGeolocation:response.data.results,
       markers:[{  position:{lat:event.latLng.lat(),lng:event.latLng.lng()}  }, ...markers],
       latClick:event.latLng.lat(),
       lngClick:event.latLng.lng()
     }))   
     this.props.onResultChange(event.latLng.lat(),event.latLng.lng(), **NEED A VALID 3RD ARGUMENT**)    
   }

and the relevant function to the parent component looks like this:

 onResultChange(x,y,info){
    this.setState(
      {
        lat:x,
        lng:y,
        clickedInfoObject:info
      }
    )
  }

lat:x and lat:y from onResultChange() are correctly updated from the child component from the values passed on the function ie event.latLng.lat() and event.latLng.lng() . However I can't use response.data.results from my axios request because that value is valid only within the scope of the axios request. How can I insert the 3rd argument for the function onResultChange(event.latLng.lat(),event.latLng.lng(), **NEED A VALID 3RD ARGUMENT**) to lift the state up with all 3 arguments?

If it's okay to call onResultChange when a request comes back then this should work:

mapClicked = event => {
  const lat = event.latLng.lat();
  const lng = event.latLng.lng();
  let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=MYGOOGLEAPIKEY`;
  axios.get(url).then(response => {
    const { markers } = this.state;
    this.setState({
      googleReverseGeolocation: response.data.results,
      markers: [{ position: { lat, lng } }, ...markers],
      latClick: lat,
      lngClick: lng
    });
    this.props.onResultChange(lat, lng, response);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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