我正在尝试将 React Hooks 与 Google Places API 结合使用,以自动完成位置搜索,找到该位置的 Google Place ID,然后使用该值更新我的组件状态。
我有谷歌 API 工作,我能够获得地点 ID,但我不确定如何从我的函数更新我的状态。
function onMapsLoad() {
// init autocomplete
const autocomplete = new window.google.maps.places.Autocomplete(document.getElementsByClassName('search')[0]);
autocomplete.addListener('place_changed', function() {
// define place and place ID
const place = autocomplete.getPlace();
const placeID = place.place_id;
// how can I update the component state from inside this function?
});
}
function myComponent() {
const [placeID, setPlaceID] = useState(null);
useEffect(() => {
const script = document.createElement(`script`);
const headScript = document.getElementsByTagName(`script`)[0];
script.type = `text/javascript`;
script.src = `https://maps.google.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}&libraries=places`;
script.addEventListener('load', onMapsLoad);
});
);
}
要么在组件内移动函数(从而使 setPlaceID 在范围内(:
function myComponent() {
const [placeID, setPlaceID] = useState(null);
function onMapsLoad() {
// ... same as before, but then ending with a call to:
setPlaceID(placeID);
}
useEffect(() => {
// ...
});
}
或者将 setPlaceID 作为参数传入
function onMapsLoad(setPlaceID) {
// ...
setPlaceID(placeID);
}
function myComponent() {
const [placeID, setPlaceID] = useState(null);
useEffect(() => {
// ... same as before, except the last line:
script.addEventListener('load', () => onMapsLoad(setPlaceID));
});
}