سؤال

I have a page where I need to load some initial Ajax data.
I read on this Reactjs page that I should make the call in componentDidMount.

What is the advantage of making the request from componentDidMount rather than componentWillMount ?

هل كانت مفيدة؟

المحلول 2

Since react is meant to be used as a view, your ajax requests are supposed to be placed in your model.

Else, if for some reason you need to make it in a view, the difference between componentDidMount and componentWillMount is that the first one is being invoked once the element is re-rendered and you have access to it via this.getDOMNode(), and the second one is invoked once right before render() starts.

نصائح أخرى

When using server rendering, componentWillMount is called but componentDidMount is not. Because of this, I tend to do any initialization that requires a browser (including Ajax and DOM manipulation) in componentDidMount.

In componentDidMount() you have access to the DOM if you need it; in componentWillMount() you don't yet have access (although you may not need it if all you want to do is call setState).

Make sure that in your render() method you're capable of gracefully rendering the "empty" state (ie. before the Ajax results have arrived back). getInitialState() can be helpful here for setting up some base empty state.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top