react 把前后台的axios请求放在一起_在React.js中将Async / Await与Axios一起使用

Following

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"

}

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(

{this.getData()}

);

}

}

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:

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

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

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

async getData(){

const res = await axios('/data');

return await res.json();

}

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

{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:

{this.state.data}

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 (

{this.state.data ? Loading... : this.state.data}

);

}

}

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 (

{this.state.data ? Loading... : this.state.data}

);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中,asyncawait经常与异步操作一起使用,以便更好地处理异步代码。通常,用async关键字声明一个函数为异步函数,这意味着这个函数将返回一个Promise对象。而使用await关键字可以等待一个异步方法执行完成。在React中,当需要在组件中进行异步操作时,可以将异步操作放在async函数中,然后使用await等待其执行完成。这样可以避免回调地狱,并且使代码更加清晰易读。 例如,在React使用async/await可以更方便地处理异步请求,比如使用axios库发送网络请求。可以在一个async函数中使用await等待请求的结果返回,并进行相应的处理。这样就可以避免使用传统的回调函数来处理异步操作,使代码更加简洁易懂。 另外,需要注意的是,在使用await的时候必须要在一个async函数中。因为await只能在async函数中使用,这是语法规定。所以在React中,一般会将异步操作放在组件的生命周期方法中,比如componentDidMount或者componentDidUpdate中,并在这些方法中使用asyncawait来处理异步逻辑。 总结来说,asyncawaitReact中的使用主要是为了更好地处理异步代码,使代码更加清晰易读,并且避免回调地狱。通过将异步操作放在async函数中,并使用await等待异步操作执行完成,可以更好地处理异步请求,提高代码的可维护性和可读性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [ReactNative进阶(三十六):ES8 中 asyncawait 使用方法详解](https://blog.csdn.net/sunhuaqiang1/article/details/117227973)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值