首页 > 解决方案 > 在 react 中使用 Axios 在一个 componentDidMount 中调用多个 API

问题描述

这是我对日期范围选择器的单个 API 调用的 React js 代码。现在我想用 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```

标签: javascriptreactjsapiaxiosfastapi

解决方案


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

推荐阅读