2017-07-24 112 views
1

我有以下代码可以根据Google Places API检索Google Places地点评论。我已经将这些逻辑合并为一个React生命周期组件。目前,我无法设置状态并正确绑定对象。我可以用一些帮助来理解我的逻辑失败的地方。反应:Google Places API/Places详情

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> 
) 
} 
} 
+0

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

回答

1

您不能在回调中以这种方式使用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,您可能没关系。

+0

感谢Mark!箭头函数肯定帮助,但我仍然无法返回的地方对象的值。 –

1

随着一些调整 - 我得到的代码工作!谢谢。

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