简体   繁体   中英

How to store value from callback function in react state? (Google Maps)

I am trying to store the value from a callback function in the state in React, but keep having errors.

I am using @react-google-maps/api and want to store the geoJson in the state, so in my code I am trying to get access to 'obj' and make usable outside the callback.

This is my code...

getGeoJson = (map, maps) => {

    //toGeoJson() takes a callback
    map.data.toGeoJson(function(obj){
        return obj
    });

    //Trying to store in state like this...
    this.setState({
        value: obj
    });
};

References .toGeoJson()

You need to set value in the callback. Here, the arrow function is important because you can keep context without binding.

getGeoJson = (map, maps) => {
    map.data.toGeoJson((obj) => {
        this.setState({
            value: obj
        });
    });
};

The variable obj is function scoped, you are trying to set it's value outside the callback function, which is the reason the value is probably being set to undefined or null or something among those lines.

You will need to store the obj variable into state inside the callback function. Like this:

 getGeoJson = (map, maps) => {
    //toGeoJson() takes a callback
    map.data.toGeoJson(obj => {
        return obj
    this.setState({
        value: obj
    });
    });
};

However, for some reason if you do not want to set it's value within the callback function, you can return the value of obj from the callback function, but you also need to capture the returned value into another variable before you can store it in the state, like so:

 getGeoJson = (map, maps) => {
//toGeoJson() takes a callback
   const object = map.data.toGeoJson(function(obj){
        return obj
    });

   this.setState({
        value: object
    });
};

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