【发布时间】:2021-09-23 11:03:10
【问题描述】:
填写表格后,memorialpage 对象被制作并添加到数据库中。从我的表格中,我得到了我的数据,一切都很好,除了得到的地址。通过使用 react-geocode,我得到了我需要的纬度和经度,但是在我得到 lat 和 lng 之前,这些对象被制作和发布,所以在数据库中这些只是 NULL。
我知道我的错误是我没有等待地理编码器,但我已经尝试将它变成一个函数但仍然没有运气。
感谢您的帮助!
const onSubmit = async (data) => {
if (image !== null) {
await handleUpload();
};
//Transforming the address that we get to latitude and longitude
Geocode.setApiKey("x");
Geocode.setLanguage("nl");
Geocode.setRegion("be");
//Google geocoder returns more than one address for given lat/lng, according to google docs, ROOFTOP param returns most accurate result
Geocode.setLocationType("ROOFTOP");
Geocode.fromAddress(data.Adres).then(
(response) => {
const { lat, lng } = response.results[0].geometry.location;
console.log(lat, lng);
setAdresLatitude(lat);
setAdresLongitude(lng);
},
(error) => {
console.error(error);
}
);
//Object for memorialPage
let memorialPage = {
FirstName: dataMemorial.FirstName,
LastName: dataMemorial.LastName,
BirthDate: dataMemorial.BirthDate,
DateOfDeath: dataMemorial.DateOfDeath,
Obituary: null,
Quote: data.Quote,
QuoteAuthor: data.QuoteAuthor,
IntroText: data.IntroText,
Latitude: adresLatitude,
Longitude: adresLongitude,
IsUndertaker: null,
Undertakers_Id: null,
};
await app.put(`/api/update-memorialpages/`, memorialPage, axiosConfig);
//Post adminhasMemorialPage
await app
.post(`/post/admin-has-memorialpage/`, idChecker, axiosConfig)
.then((res) =>
history.push({
pathname: "/memorialpage-form-3",
state: memorialPage,
})
);
};
【问题讨论】:
-
您在控制台上收到
lat,lng吗? -
最后一行中的
making it a function是什么意思?您应该直接等待Geocode.fromAddress并将其作为回复。 -
是的,我在那里得到了正确的数据。我所说的创建函数的意思是,我尝试在 onSubmit 之外创建一个函数并将数据作为道具提供,然后像 handleUpload 一样在 onSubmit 中调用该函数并等待它。
-
那么我建议你在发送数据之前添加一个检查
lat,lng是否可用。
标签: reactjs async-await google-geocoder