简体   繁体   English

如何在反应状态下存储回调函数的值? (谷歌地图)

[英]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.我试图将回调函数中的值存储在 React 的状态中,但一直有错误。

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.我正在使用 @react-google-maps/api 并希望将 geoJson 存储在 state 中,因此在我的代码中,我试图访问 'obj' 并使其在回调之外可用。

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()参考.toGeoJson()

You need to set value in the callback.您需要在回调中设置value 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.变量 obj 是函数作用域,您试图在回调函数之外设置它的值,这就是该值可能被设置为 undefined 或 null 或这些行中的某些内容的原因。

You will need to store the obj variable into state inside the callback function.您需要将 obj 变量存储到回调函数内的 state 中。 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:但是,出于某种原因,如果您不想在回调函数中设置它的值,则可以从回调函数中返回 obj 的值,但您还需要将返回值捕获到另一个变量中,然后才能将其存储在状态,像这样:

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

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

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

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