简体   繁体   English

Axios在React中有多个请求

[英]Axios multiple Requests in React

I am trying to create 2 requests and set variables with this.setState({}) for further changes. 我正在尝试创建2个请求,并使用this.setState({})设置变量以进行进一步的更改。

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> 

UPDATE as @JaromandaX pointed out you'd better stick with native Promise.all and destructuring. @JaromandaX指出, UPDATE最好坚持使用Promise.all和解构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM