I have some questions about react usage and patterns.
Should I use
componentDidMount
or
getInitialState
in loading data asynchronously? What is the difference between the two?
I am using Backbone for my frontend data structures
this.props.data = new BrandModel({ _id: this.props.params.brandId });
var that = this;
this.props.data.fetch({
success: function () {
that.setState({ brand: that.props.brand });
}
});
return null;
Update: thanks for the responses
This Question is suggesting to not us componentWillMount, but I understand that its more expressive to use componentDidMount in this case as getInitialState seems to be meant to be used synchronously
Update 2:
I've had to revert to using getInitialState as componentDidMount fires after render and I need this.props.data to be pointing to an object
componentDidMount
would be called after component was mounted into browser DOM (it would be called after first render and it would not be called if you are rendering server-side(to string)
getInitialState
would be called when component is created, if you are using es6 class syntax you can place that logic in you component constructor directly assigning to this.state
There is also componentWillMount
it would be called before first render for both server and client - it is more suitable in your case.
Componentndid mount is fired after the render and we load the Ajax inside that.While during the actual render we check if the object has data, else send empty div
componentDidMount: function () {
console.log("========> FIring");
$.get("http://api.", function(response) {
if (this.isMounted()) {
this.setState({
Data: response
});
}
}.bind(this));
},
render: function() {
var data = this.state.Data;
if (this.state.promoData) {
return (<div>{data}</div>
);
} else {
return (<div className="divLoading">Loading...</div>);
}
}
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