javascript - 在 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```
解决方案
使用.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))
}
推荐阅读
- r - 为什么在粘贴输出的末尾添加“.NULL”?
- c - C编程语言,如何在代码中转换输入字符串并运行它
- python - 更新 int 标签时遇到问题,但可以正常更新字符串标签
- penetration-testing - 提供渗透测试报告?
- android - 如何在实时数据库中保存超过 20000 个字符的大文本?
- mysql - 如何确认我的 AWS MySQL 连接是安全的?
- java - 类型的非法开始(其他)
- javascript - 如何使用 React-Navigation 避免组件重复?
- postgresql - 这个 postgres CLI 命令中的 VERSION NUMBER 引用是什么?
- python - pd.read_excel 将第一列合并为一个