2017-07-24 113 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> 
) 
}