javascript - 在 React.js 中将 Async/Await 与 Axios 一起使用

标签 javascript json reactjs asynchronous ecmascript-2017

关注

How to use async/await with axios in react

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

JSON

{
   id: 1,
   name: "Aditya"
}

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

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

使用这种方法我得到以下错误:

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 永远不会返回任何东西,所以它的 promise (async 函数总是返回一个 promise )将通过 undefined 来实现,如果它不拒绝

  2. 错误信息清楚地表明你正在尝试直接渲染 promise getData 返回,而不是等待它解决然后渲染履行值

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

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

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

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

...因为这不会等待解决方案。您需要改为使用 getData 来设置状态:

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

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

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

更新:现在您已经向我们展示了您的代码,您需要执行类似这样的操作:

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 而不是 then捕获。您可以通过在其中嵌套一个 async IIFE 函数并确保该函数不会抛出来做到这一点。 (componentDidMount 本身不能是 async,什么都不会消耗这个 promise。)例如:

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

关于javascript - 在 React.js 中将 Async/Await 与 Axios 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46733354/

相关文章:

javascript - 静态站点 Cookie : Cookie will be soon rejected(SameSite) issue

c# - 使用 NewtonSoft 解析 JSON 时出错

reactjs - Xcode10 : build input file double-conversion cannot be found

javascript - 如何在 React 中动态导入图像?

javascript - 如何在reactjs中将子项追加到光标位置

javascript - 如何在 foreach 循环中仅显示一次对象?

javascript - 将单元格值从表格复制到文本框

javascript - Jest 使用 react + konva 和/或 react-konva 遇到了意外的 token

json - 使用 Go 获取 JSON 数组中的特定键

json - 配置 vscode json 格式化空间