这是我的 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/