我有以下代码,检索谷歌地点评论的基础上谷歌地点API。我已经合并了作为React生命周期组件工作的逻辑。目前,我无法setState并正确绑定对象。我可能需要一些帮助来理解我的逻辑在哪里失败。
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>
)
}
}发布于 2017-07-24 23:12:59
您不能在回调中以这种方式使用this。当函数在中被称为this时,this.setState({places.place.reviews})并不指向您的对象。一种解决方案是使用=>函数表示法,它将从词法上绑定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,所以您可能还可以。
发布于 2017-07-24 23:26:41
经过一些调整--我让代码正常工作了!谢谢。
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>
)
}https://stackoverflow.com/questions/45283941
复制相似问题