我无法理解如何从回调函数设置状态。
Google默认情况下会向get data from their place API提供此代码
我想知道的是:
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
}
}
}
}
声明回调而不将其绑定到组件会返回'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)
);
}
基本上,将它绑定到构造函数内的回调
this.callback = this.callback.bind(this);
您必须编辑以下内容
const getPlaceById = new
google.maps.places.PlacesService(map).getDetails(
request,
this.callback
);