我正在尝试创建 2 个请求并使用 this.setState({})
设置变量以进行进一步更改。
这是我得到的:
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>
我通过多个问题查找了我正在尝试做的事情,但没有解决我正在尝试实现的问题。
最佳答案
您的代码中存在绑定(bind)问题。
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
和解构。
关于javascript - React 中的 Axios 多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45795179/