gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:50:48 25 4
gpt4 key购买 nike

关注

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com