I have a React Class that's going to an API to get content. I've confirmed the data is coming back, but it's not re-rendering:
var DealsList = React.createClass({ getInitialState: function() { return { deals: [] }; }, componentDidMount: function() { this.loadDealsFromServer(); }, loadDealsFromServer: function() { var newDeals = []; chrome.runtime.sendMessage({ action: "findDeals", personId: this.props.person.id }, function(deals) { newDeals = deals; }); this.setState({ deals: newDeals }); }, render: function() { var dealNodes = this.state.deals.map(function(deal, index) { return ( <Deal deal={deal} key={index} /> ); }); return ( <div className="deals"> <table> <thead> <tr> <td>Name</td> <td>Amount</td> <td>Stage</td> <td>Probability</td> <td>Status</td> <td>Exp. Close</td> </tr> </thead> <tbody> {dealNodes} </tbody> </table> </div> ); } });
However, if I add a debugger
like below, newDeals
are populated, and then once I continue, i see the data:
loadDealsFromServer: function() { var newDeals = []; chrome.runtime.sendMessage({ action: "findDeals", personId: this.props.person.id }, function(deals) { newDeals = deals; }); debugger this.setState({ deals: newDeals }); },
This is what's calling deals list:
var Gmail = React.createClass({ render: function() { return ( <div className="main"> <div className="panel"> <DealsList person={this.props.person} /> </div> </div> ); } });
If React fails to do re-render components automatically, it's likely that an underlying issue in your project is preventing the components from updating correctly.
State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
I'd like to add to this the enormously simple, but oh so easily made mistake of writing:
this.state.something = 'changed';
... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:
this.setState({something: 'changed'});
React only triggers a re-render if you use setState
to update the state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With