简体   繁体   中英

How to call multiple ajax at same time (and get results asychronous) in ReactJS?

I want to send multiple ajax calls in ReactJS, and I wonder if the code is executed in order. Will the second ajax call be sent only after the first ReactJS component is rendered?

var firstAJAX = React.createClass({
  componentWillMount: function() {
    this.state = {list: []};
  },
  componentDidMount: function() {
    $.ajax({
      url: '/someurl',
      dataType: 'json',
      cache: false,
      type: 'GET',
      success: function(data) {
        this.setState({list: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('url', status, err.toString());
      }.bind(this)
    })
  },
  render: function() {
    return (
        <div>
             {something}
        </div>
    )
  }
})
ReactDOM.render(<firstAJAX />,
  document.getElementById('div')
);

var secondAJAX = React.createClass({
   //similar code with different url from firstAJAX
});

I want to handle multiple document elements with the results got from ajax. How to make the send 1 ajax->render->send 1 ajax->render->... become send multiple ajaxs -> render -> render...

I think your way is to use container components pattern. In this case you can run two requests for firstAJAX & secondAJAX in container and define behaviour of child elements as you want

Assuming you add the following code after your var secondAJAX = ... declaration, the 2nd ajax call would happen after the first one rendered.

ReactDOM.render(<secondAJAX />,
  document.getElementById('div')
);

I don't know what you're hoping to accomplish with this question, but you probably don't want to be doing things this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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