根据google places API调用更新状态

问题描述 投票:3回答:2

我无法理解如何从回调函数设置状态。

Google默认情况下会向get data from their place API提供此代码

我想知道的是:

  • 如何根据从该API接收的数据更新“isOpen”的状态? 我不能做“this.setState”,因为'this'不是指全局状态 然后我将使用state“isOpen”(true / false)来声明带有条件JSX的变量。 export default class IndexPage extends Component { constructor(props) { super(props); this.state = { isOpen: false, }; } componentDidMount() { let map = new window.google.maps.Map(document.getElementById("map"), { }); const request = { placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4" }; const getPlaceById = new google.maps.places.PlacesService(map).getDetails( request, callback ); function callback(place, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { console.log(place.opening_hours.open_now); //returns true or false //set isOpen to state } } } }
javascript reactjs callback this state
2个回答
1
投票

声明回调而不将其绑定到组件会返回'setState of undefined'错误。

将回调函数声明为您的react组件的类方法。

class X extends React.Component {
    ...

    callback(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {               
            // set state here
            this.setState({ isOpen: place.opening_hours.open_now})
        }
    }

    ...
}

然后在你的componentDidMount()调用中,绑定你的回调方法,如下所示:

componentDidMount() {
    const map = new window.google.maps.Map(document.getElementById("map"), {});    
    const request = { placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4" };
    const getPlaceById = new google.maps.places.PlacesService(map).getDetails(
        request,
        // you need to bind `this` to callback function to use callback in HTML DOM
        (place, status) => this.callback(place, status)
    );
}

0
投票

基本上,将它绑定到构造函数内的回调

this.callback = this.callback.bind(this);

您必须编辑以下内容

const getPlaceById = new 
google.maps.places.PlacesService(map).getDetails(
request,
this.callback
);

有关更多信息,请阅读https://reactjs.org/docs/handling-events.html

© www.soinside.com 2019 - 2024. All rights reserved.