0

我正在尝试在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块内的状态值。

4

3 回答 3

1

问题是当您set-state在那之后无法立即看到状态结果时。这就是console.log回报的原因null。确保您console.logrender block. 这是因为为了提高性能,set-state动作是批处理的。asynchronous这在 setState 的文档中进行了解释。看看这个 =>为什么 reactjs 中的 setState 是 Async 而不是 Sync?

于 2019-06-01T04:56:24.743 回答
0

您需要将函数上下文绑定到当前类/组件。试试下面的东西。创建一个类似“callSetState”的函数,将其与 this 绑定,然后在调用时将值作为参数传递给它。

import React, { Component } from 'react';
class Test extends Component{
    constructor() {
        super()
        this.callSetState = this.callSetState.bind(this);
    }

    callSetState(latitude, longitude) { 
        this.setState({
            location_latitude: latitude,
            location_longitude: longitude,
        })
    }

/* Call this func in your class and call callSetState which is already bound to your component in constructor */

    // geocodeByAddress(location)
    //     .then(results => getLatLng(results[0]))
    //     .then(latLng => this.callSetState(latLng.lat, latLng.lng));

}
于 2019-05-31T20:08:56.950 回答
-1

这显然是您的数据呼叫没有反应的问题。

您的反应代码看起来不错,但我建议吐出代码。

1) service.js 文件 - 这会执行您的查询并返回数据或返回错误。

2) location 组件,componentDidMount() 或 useEffect(() => {}, []) 获取数据并更新 state/useState()

——</p>

为了给你一个代码片段,我需要你提供一个latLang&的控制台日志results

非常感谢

于 2019-06-01T01:00:01.790 回答