javascript - 如何在 React componentDidMount() 方法中使用异步等待?

标签 javascript reactjs

我想将 async/wait 与 React componentDidMount() 方法一起使用,但我收到了 await is a reserved word 错误。我还尝试将语句包装在立即调用的函数中,但没有帮助。

async componentDidMount() {
  this.geoLocation.getAddress().then(location => {
    if (location.address != null && location.error != "undefined") {
      let fifteenMins = [];
      await this.getFifteenMinsData(y, x).then(
        data => {
          fifteenMins = data["forecasts"];
        }
      );
        console.log(fifteenMins);
    } 
  });
}

如果我删除 await 关键字,那么我会在 console.log 中得到 null,但是如果我在 fifteenMins = data["forecasts "]; 然后我得到数据。

相关问题: Await is a reserved word error inside async function

最佳答案

async 函数总是返回 promise 。由于 componentDidMount 没有设计/记录为 async 函数,因此 React 不会对其返回的 promise 做任何事情。如果为此使用 async 函数,请确保将其所有代码包装在 try/catch 中,以便捕获所有错误并且您不会' 以未处理的异常结束(变成未处理的拒绝)。

问题是您试图在非async 函数中使用await:您传递给then 的回调。当使用async/await时,你几乎从不使用then。相反:

async componentDidMount() {
  try {
    const location = await this.geoLocation.getAddress();
    if (location.address != null && location.error != "undefined") {
      const data = await this.getFifteenMinsData(y, x);
      let fifteenMins = data["forecasts"];
      console.log(fifteenMins);
    } 
  } catch (err) {
      // Do something with the fact an error occurred
  }
}

或者使用 IIFE 避免从 componentDidMount 返回一个 promise:

componentDidMount() {
  (async () => {
    const location = await this.geoLocation.getAddress();
    if (location.address != null && location.error != "undefined") {
      const data = await this.getFifteenMinsData(y, x);
      let fifteenMins = data["forecasts"];
      console.log(fifteenMins);
    } 
  })()
  .catch(error => {
    // Do something with the fact an error occurred
  });
}

或者根本不使用 async 函数(但是 async 函数真的很方便):

componentDidMount() {
  this.geoLocation.getAddress()
    .then(location => {
      if (location.address != null && location.error != "undefined") {
        return this.getFifteenMinsData(y, x)
          .then(data => {
            let fifteenMins = data["forecasts"];
            console.log(fifteenMins);
          });
      } 
    })
    .catch(error => {
      // Do something with the fact an error occurred
    });
}

旁注:这对线:

const data = await this.getFifteenMinsData(y, x);
let fifteenMins = data["forecasts"];

如果你愿意,可以这样写,将结果解构到fifteenMins变量中:

let {fifteenMins: forecasts} = await this.getFifteenMinsData(y, x);

同样,如果您确实决定使用非async 版本,您可以在then 处理程序的参数列表中执行此操作:

.then(({fifteenMins: forecasts}) => {
  console.log(fifteenMins);
});

关于javascript - 如何在 React componentDidMount() 方法中使用异步等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51862338/

相关文章:

javascript - Backbone.js:在模型中设置模型属性?

javascript - 访问 Parse.Cloud.httpRequest{()} 内的全局变量

javascript - 我无法使用函数动态设置我的 ReactJS 状态

javascript - ReactJS 中 undefined variable

javascript - 使用 redux 创建秒表

javascript - React Router 链接右键单击不起作用

javascript - YouTube嵌入和PHP显示iframe但显示错误

php - 当我从 php 和 javascript 表单中获取值时,确认框不起作用

css - 如何用两种颜色制作一个背景?

javascript - Mongodb 聚合,在 $group _id 的表达式中使用变量的值