本文介绍了反应中的Axios多个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建2个请求并使用 this.setState({})
设置变量以进行进一步更改。
I am trying to create 2 requests and set variables with this.setState({})
for further changes.
这就是我得到的:
This is what i got:
class App extends React.Component {
constructor() {
super();
this.state = {user: false, repository :false}
}
componentDidMount() {
axios.all([
axios.get('https://api.github.com/users/antranilan'),
axios.get('https://api.github.com/users/antranilan/repos')
])
.then(axios.spread(function (userResponse, reposResponse) {
this.setState({user : userResponse.data, repository : reposResponse.data});
});
}
render() {
return (
<div>
{this.state.user.login}
{this.state.repository.length}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
我通过多个问题查询了我的情况试图做,但没有解决我想要实现的目标。
I looked up through multiple questions with what i am trying to do but there was no solution to what i am trying to achive.
推荐答案
您的代码中存在绑定问题。
You have binding issue in your code.
class App extends React.Component {
constructor() {
super();
// You should use object to delineate the type
this.state = {user: {}, repository :{} }
}
componentDidMount() {
// Better use native Promise.all
Promise.all([
axios.get('https://api.github.com/users/antranilan'),
axios.get('https://api.github.com/users/antranilan/repos')
])
// use arrow function to avoid loosing context
// BTW you don't need to use axios.spread with ES2015 destructuring
.then(([userResponse, reposResponse]) => {
this.setState({user : userResponse.data, repository : reposResponse.data});
});
}
render() {
const { user, repository } = this.state
return (
<div>
{user && user.login}
{repository && repository.length}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
更新为@ JaromandaX指出你最好坚持使用原生 Promise.all
和解构。
UPDATE as @JaromandaX pointed out you'd better stick with native Promise.all
and destructuring.
这篇关于反应中的Axios多个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!