根据google places API调用更新状态

时间:2017-12-21 04:57:45

标签: javascript reactjs callback this state

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

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

2 个答案:

答案 0 :(得分:1)

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

将回调函数声明为反应组件的类方法。

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

答案 1 :(得分: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