在反应中使用 Axios 在一个 componentDidMount 中调用多个 API

multiple API calls in one componentDidMount using Axios in react

这是我的 React js 代码,用于单个 API 调用日期范围选择器。现在我想用 componentDidMount 方法在 React 中调用多个 API 是否可能,如果是的话,该怎么做

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```

您可以根据需要在 componentDidMount 中添加更多的 api。

componentDidMount(){
        axios.get('http://127.0.0.1:8000/betweendays')
        .then(response => {
            this.setState({
                posts:response.data
            })
            console.log(response.data)
        })
    axios.get('link')
        .then(response => {
            this.setState({
                posts:response.data
            })
            console.log(response.data)
        })
    }

使用.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))
}