Hello.

To populate the contents of the React component, I use AJAX in the body of the componentWillMount method, where I change the state upon execution of the request. The trouble is that the render of the component is executed both before the completion of the request, and after the state change by the setState method. Moreover, if such a component renders another one, which also uses AJAX, then the number of render calls grows as a power of two.

How to force a component to be rendered only after obtaining the necessary data?

var News = React.createClass({ getInitialState: function () { return { news: [], page: 1 }; }, componentWillMount: function () { let xmlhttp = getXmlHttp(); xmlhttp.open("POST", "server/news.php", true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.onreadystatechange=() => { if (xmlhttp.readyState != 4) return; clearTimeout(timeout); if (xmlhttp.status == 200) { this.setState({ news: eval(xmlhttp.responseText.toString()) }); } else { handleError(xmlhttp.statusText); } }; xmlhttp.send('page=' + this.state.page); var timeout = setTimeout( function(){ xmlhttp.abort(); handleError("Request time over") }, 10000); }, render: function () { let itemList = this.state.news.map(function(item, iterator){ return ( <NewsItem niTitle={item[0]} niText={item[1]} niDate={item[2]} niImg={item[3]} key={"ni " + iterator} /> ); }); return ( <div> {itemList} <PageChanger page={this.state.page}/> </div> ); } }); 
  • The issue is resolved. Do not delete, suddenly someone will come in handy: stackoverflow.com/questions/39626824/… - svnvav
  • one
    It would be good to transfer this case to ComponentDidMount, but for now there is no data - to put something like the component of the <Loading /> twist - xFloooo
  • If possible, publish the solution found in response to your question . I am sure it will help many of your colleagues in the future. - Nicolas Chabanovsky

0