一个组件中有多个API调用在React中使用Axios的Didmount [英] multiple API calls in one componentDidMount using Axios in react

查看:0
本文介绍了一个组件中有多个API调用在React中使用Axios的Didmount的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是针对日期范围选取器的单个API调用的REACTIVE js代码。现在我想调用多个API与组件一起反应Didmount方法是否可能如果是,如何实现

import React,{ Component} from "react";
import axios from 'axios'

class PostList extends Component{
    constructor(props) {
        super(props)
    
        this.state = {
            posts: []
        }
    }
componentDidMount(){
    axios.get('http://127.0.0.1:8000/betweendays')
    .then(response => {
        this.setState({
            posts:response.data
        })
        console.log(response.data)
    })
}
    render() {
        const {posts} = this.state
        return (
            <div>
                <h1>get call in React js</h1>
                    {
                        posts.map(post => <div key = {post.id}>{post.id} </div>)
                    }
            </div>
        )
    }
}

export default PostList```

推荐答案

使用.then()方法创建请求链..

componentDidMount() {
    axios.get('http://127.0.0.1:8000/betweendays')
        .then(response => {
            this.setState({
                posts: response.data
            })
            return response.data; //  returning response
        })
        .then(res => {
             // do another request Note we have the result from the above 
            // getting response returned before 
            console.log(res);
        })
        // Tag on .then here 
        .catch(error => console.log(error))
}

这篇关于一个组件中有多个API调用在React中使用Axios的Didmount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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