Following

How to use async/await with axios in react

我正在try 使用React.js App中的异步/等待向我的服务器发出一个简单的GET请求. 服务器在/data处加载一个简单的JSON,如下所示

JSON

{
   id: 1,
   name: "Aditya"
}

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:

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

Am I not implementing it correctly?

推荐答案

Two issues jump out:

  1. 你的getData永远不会返回任何东西,所以如果它不拒绝,它的promise (async个函数总是返回一个promise )将以undefined实现

  2. 错误消息清楚地表明,您正试图直接呈现promise getData returns,而不是等待它结算,然后呈现实现值

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

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

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

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

.因为这并不需要等待决议.相反,您需要使用getData来设置状态:

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>
        );
    }
}

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>
        );
    }
}

Json相关问答推荐

JOLT转换过滤出特定值/对象

Flutter -控制器问题-JSON API

在Ruby的json中压缩单个字段

如何将一个对象添加到多个对象中 JOLT

将 GEOSwift.JSON 转换为 Swift 中的 struct

如何加入或合并列表元素列表(未知长度)

添加到数组时出错:找不到Add的重载和参数计数:1

Nifi - 忽略(或删除)JSON 的第一个数字

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

坚持弄清楚如何使用 api 响应来调用以从不同的链接检索响应

为什么在测试 RSPEC 时 JBuilder 不返回 JSON 中的响应正文

Angular 2/Web Api - json 解析错误语法错误意外结束输入

Retrofit 2.0 如何解析嵌套的 JSON 对象?

Django - 异常处理最佳实践和发送自定义错误消息

C#扁平化json struct

MySQL Select JSON 字段属性具有值的位置

无法将空值放入 JSON 对象

Jersey 2.0 相当于 POJOMappingFeature

如何从 MySQL 中检索 JSON 数据?

使用 JSONArray 和 JSONObject 进行 Foreach