我正在尝试在then()Promise 的 a 中设置状态,但状态值没有被保存,并且在 then() 之外无法访问。
以下是更新后的代码:
handleSelect = location => {
this.setState({ location });
geocodeByAddress(
location
)
.then(results => getLatLng(results[0]))
.then(latLng => {
this.setState({
location_latitude: latLng.lat,
location_longitude: latLng.lng,
})
console.log(this.state.location_latitude); // returns the correct value
})
console.log(this.state.location_latitude); // returns null (the originally declared value)
}
如果我console.log(this.state.location_latitude)得到一个null值。但是,如果我在 then() 块中使用 console.log,我会得到正确的值。在这种情况下如何设置状态?
更新说明:
为了给这里的整个逻辑提供一个更好的上下文:我正在使用一个 Google Places Autocomplete 组件,它允许用户从下拉列表中选择一个位置。handleSelect当用户从下拉列表中选择一个位置时,将调用上述方法。然后我使用该方法提取用户选择的地点的经纬度geocodeByAddress,这是一个承诺。然后我需要检索纬度和经度并相应地设置状态,稍后用于发送到数据库。我还不能将值提交到数据库,因为用户需要填写其他表单输入(它们也存储在状态中),一旦他点击提交,我将提交所有状态元素单次调用后端。所以,没有什么我想更新的componentDidMount()或者没有更新尚未使用componentDidUpdate()。无论如何,我只能将状态值存储在 then of 中geocodeByAddress(如果我在这里错了,请纠正我)。所以,我必须能够修改then块内的状态值。