【问题标题】:react set initial state with async/await variable使用 async/await 变量反应设置初始状态
【发布时间】:2021-03-17 05:53:03
【问题描述】:

我在 Javascript 中使用 async/await 来根据用户的 IP 地址获取用户的坐标。然后我使用这些坐标作为一些 React 组件的初始状态值。 call fetch 调用有效,但没有等待。我想我对 async/await 的使用有问题。如何确保 fetch 调用在继续之前返回? 这是我的代码:

let ip_address_coords
const get_ip_coords = () => {
  try {
    let resp = fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=<my_api_key>")
    let data = resp.json()
    return {lng: data.location.lng, lat: data.location.lat}
  } catch (err) {
    console.log(err)
  }
}

(async () => {
  ip_address_coords = await get_ip_coords();
})()

class Application extends React.Component {
  constructor(props) {
    super()
    this.state = {
      lng: ip_address_coords['lng'],
      lat: ip_address_coords['lat']
    }
    ...

【问题讨论】:

  • 我认为这种方法没有意义:您应该将 ip_address_coords 定义为父组件状态(应用程序?)的一部分,然后您应该在父组件的 componentDidMount 方法中添加获取逻辑,一旦获取成功,您应该设置您的ip_address_coords 状态值。现在您已经完成了该逻辑,您可以将ip_address_coords 作为您想要的子组件中的道具传递。
  • @IrvinSandoval 该方法可行,并且是我目前正在使用的方法,但是我将这些坐标用于地图,这会导致地图在渲染时双离合,这意味着它会渲染一个位置简单,然后下一个。我想直接去用户的位置。

标签: javascript reactjs async-await


【解决方案1】:

问题作为我的观点,你正在使用异步外部函数,我认为你必须处理它的子函数。

这样使用是因为每个函数都有自己的上下文,因此您必须单独处理该函数,以便您可以通过两种方式处理异步任务: 在以下方法上使用异步等待 在内部函数上使用 Promis 的更好的处理方式,然后你的异步等待可能会起作用

const get_ip_coords = async () => {
try{
let resp = await fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=<my_api_key>")
let data = resp.json()
   return {lng: data.location.lng, lat: data.location.lat}
 } catch (err) {
    console.log(err)
  }
}

 const get_ip_coords = () => {
    return new Promiss((resolve,reject)=>{
             fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey= 
               <my_api_key>").then(res=>{
                    let data = resp.json()
                    resolve({lng: data.location.lng, lat: data.location.lat})
                }).catch(err=>{
                      reject(err)
                })
    })
}

你也可以使用回调机制。

【讨论】:

  • 谢谢,但第一个并不能解决问题,而在第二个中,即使修复了“Promise”上的错字,promise 也会被拒绝。
【解决方案2】:

我仍然不确定为什么这不像最初写的那样工作,但我找到的解决方案是使实际使用坐标的组件的 componentDidMount 方法异步。

看起来像这样:

  get_ip_coords = () => {
    return new Promise(async (resolve, reject) => {
      const resp = await fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=<my_api_key>")
      const data = await resp.json()
      resolve([data.location.lng, data.location.lat])
    })
  }
  
  componentDidMount = async () => {
    const map = new mapboxgl.Map({
      center: await this.get_ip_coords(),
      ...

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 2014-08-30
    • 2018-06-10
    • 1970-01-01
    • 2015-09-29
    • 2018-03-20
    • 2021-12-14
    • 2018-06-24
    相关资源
    最近更新 更多