javascript - 在 react 中使用 Axios 在一个 componentDidMount 中调用多个 API

标签 javascript reactjs api axios fastapi

这是我的 React js 代码,用于日期范围选择器的单个 API 调用。现在我想在 React 中使用 componentDidMount 方法调用多个 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```

最佳答案

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

关于javascript - 在 react 中使用 Axios 在一个 componentDidMount 中调用多个 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69310222/

相关文章:

java - Jenkins 403 请求中未包含有效的面包屑

api - 在服务器上存储 API key

javascript - 将变量传递给 jQuery 单击处理程序

javascript - 如何将参数传递给图像加载事件?

javascript - 单击按钮后如何显示来自mongodb的数据到reactjs?

javascript - React Component as Const select onChange 传递选定值

java - AMQP - Rabbit MQ 用法

javascript - 语法错误 : Cannot use import statement outside a module: when running Jest-expo tests

javascript - 如何将 JSON 对象解析为 mysql 查询

reactjs - 使用 React、Jest、Redux 和 Thunk 进行无限循环测试