【问题标题】:Update state based on google places API call根据 google Places API 调用更新状态
【发布时间】:2018-06-03 17:33:02
【问题描述】:

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

Google 默认将此代码提供给get data from their place API

我想知道的是:

  • 如何根据从该 API 接收的数据在此处更新“isOpen”的状态?

    • 我不能执行“this.setState”,因为“this”不是指全局状态
    • 然后我将使用状态“isOpen”(真/假)来声明一个带有条件 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


    【解决方案1】:

    基本上,将 this 绑定到构造函数中的回调

    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

    【讨论】:

      【解决方案2】:

      声明回调而不将其绑定到组件会返回“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)
          );
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-15
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        相关资源
        最近更新 更多