反应中的Axios多个请求

时间:2017-08-21 10:48:15

标签: javascript reactjs

我正在尝试创建2个请求并使用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'));设置变量以进行进一步更改。

这就是我得到的:

&#13;
&#13;
<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>
&#13;
<div class="prod-row-wrap">
 <div class="prod-new-row">
  <div class="prod-name">
   <select class="form-control" name="prod_name[]">
    <option value="x">Platinum subscription</option>
   </select>
  </div>
  <div class="prod-quan">
   <input type="text" name="quantity" class="form-control" />
  </div>
  <div class="prod-price">
    <input type="text" name="price" class="form-control" />
  </div>
  <div class="prod-tax">
    <input type="text" name="tax" class="form-control" />
  </div>
  <div class="prod-total">
    <p>&pound; <span class="total">0</span></p>
  </div>
  <div class="prod-delete">
    <a href="#" class="remove_field">Remove</a>
  </div>
 </div>
 <button class="btn btn-lg add_product_button">Add product</button>
</div>
&#13;
&#13;
&#13;

我通过多个问题查看了我想要做的事情,但是我没有解决我想要实现的目标。

1 个答案:

答案 0 :(得分:6)

您的代码中存在绑定问题。

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并进行解构。