【问题标题】:React: Google Places API/ Places Details反应:Google Places API/ Places 详细信息
【发布时间】:2017-12-30 05:41:47
【问题描述】:

我有以下代码,它基于 Google Places API 检索 Google Places 评论。我已经将逻辑合并为 React 生命周期组件。目前,我无法设置状态并正确绑定对象。我可以使用一些帮助来了解我的逻辑失败的地方。

export default class Reviews extends React.Component{
constructor(props){
    super(props);
    this.state = {
      places: []
    }
  }


componentDidMount(){


let map = new google.maps.Map(document.getElementById("map"), {
    center: {lat:40.7575285, lng: -73.9884469}
  });

  let service = new google.maps.places.PlacesService(map);

service.getDetails({
    placeId: 'ChIJAUKRDWz2wokRxngAavG2TD8'
  }, function(place, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      console.log(place.reviews);
      // Intended behavior is to set this.setState({places.place.reviews})
    }
  })
}
render(){
const { places } = this.state;
return(
  <div>
    <p>
      {
        places.map((place) => {
          return <p>{place.author_name}{place.rating}{place.text}</p>
        })
      }
    </p>
  </div>
  )
 }
}

【问题讨论】:

  • * 预期行为是设置 this.setState({places:place.reviews})

标签: reactjs components google-places-api setstate


【解决方案1】:

您不能在回调中以这种方式使用this。当函数在this 中调用时,this.setState({places.place.reviews}) 不会指向您的对象。一种解决方案是使用=&gt; 函数表示法,它将在词法上绑定this

service.getDetails({
    placeId: 'ChIJAUKRDWz2wokRxngAavG2TD8'
}, (place, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      console.log(place.reviews);
      this.setState({places: place.reviews})
    }
  })
}

或者,您可以对this 进行新的引用,然后在函数中使用它。像

var that = this
...
that({places.place.reviews})

第一个选项更好,但需要一个可以使用 ES6 的环境。由于您使用let,您可能还好。

【讨论】:

  • 谢谢马克!箭头函数确实有帮助,但是我仍然无法从位置对象返回值。
【解决方案2】:

经过一些调整——我得到了代码!谢谢。

render(){
const { places } = this.state;
return(
  <div>
    <p>
      {
        places.map((place) => {
          if(place.rating >= 4){
            return <p key={place.author_name}>{place.author_name}{place.rating}{place.text}</p>
          }
        })
      }
    </p>
  </div>
 )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    相关资源
    最近更新 更多