在React.js中将Async/Await与Axios一起使用 [英] Use Async/Await with Axios in React.js

查看:663
本文介绍了在React.js中将Async/Await与Axios一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下

如何在axios中对axios使用async/await

How to use async/await with axios in react

我试图在React.js应用程序中使用Async/Await向我的服务器发出一个简单的get请求. 服务器在/data处加载一个简单的JSON,如下所示:

I am trying to make a simple get request to my server using Async/Await in a React.js App. The server loads a simple JSON at /data which looks like this

JSON

{
   id: 1,
   name: "Aditya"
}

我能够使用简单的jquery ajax get方法将数据获取到我的React App. 但是,我想利用axios库和Async/Await来遵循ES7标准. 我当前的代码如下:

I am able to get the data to my React App using simple jquery ajax get method. However, I want to make use of axios library and Async/Await to follow ES7 standards. My current code looks like this:

class App extends React.Component{
 async getData(){
     const res = await axios('/data');
     console.log(res.json());
 }
 render(){
     return(
         <div>
             {this.getData()}
         </div>
     );
 }
}

使用这种方法时,出现以下错误:

Using this approach I get the following error:

对象作为React子对象无效(找到:[object Promise]).如果 您本打算渲染子级集合,而是使用数组.

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

我执行不正确吗?

推荐答案

跳出两个问题:

  1. 您的getData从不返回任何内容,因此它的诺言(async函数总是返回诺言)在解析时将由undefined解析

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

错误消息清楚地表明,您正在尝试直接呈现getData返回的诺言,而不是等待其解决然后呈现解决方案

The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

寻址#1:getData应该返回调用json的结果:

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig#2:我们必须看更多的代码,但从根本上讲,您不能这样做

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...因为这不等待解决方案.相反,您需要使用getData设置状态:

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...并在渲染时使用该状态:

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>


更新:既然您已经向我们展示了代码,则需要执行 这样的操作:


Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

进一步更新:您已表示偏好在componentDidMount中使用await而不是thencatch.您可以通过在其中嵌套async IIFE函数并确保该函数不会抛出该函数来做到这一点. (componentDidMount本身不能为async,没有任何东西会消耗该承诺.)例如:

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

这篇关于在React.js中将Async/Await与Axios一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆