Can I put ajax in the constructor of a React component?

class AjaxInConstructor extends React.Component{ constructor() { super(); this.state = {name: '', age: ''} this.loadData().then(data => { this.setState(data); }); } loadData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ name: 'slideshowp2', age: 123 }); }, 2000); }); } render() { const {name, age} = this.state; return <div> <p>Can I init component state async?</p> <p>name: {name}</p> <p>age: {age}</p> </div> } } ReactDOM.render( <AjaxInConstructor/>, document.body ) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

Above is my demo code. I know that people always put ajax in the componentDidMount or componentWillMount life cycle.

But this case also works.

In chrome console React does not produce errors and distortions. So my question is use, how is that completely correct? Is there any mistake?

+7
source share
1 answer

You can make AJAX calls wherever you want. There is nothing "wrong" in creating an AJAX call in the constructor, but there is a catch. You want to make an AJAX call only after the component has been mounted or just before it is installed.

So, before rendering the component, it is recommended to make an AJAX call to componentDidMount() or componentWillMount() . Just because React allows you to do “things” doesn’t mean you should! :)

UPDATE

I also understand that initially my answer was not strict. I have always been following the programmer blind.

After several searches, I found them one step closer to the complete answer - Why should the ajax request be executed in the ComponentMount component in React components?

The gist of these answers is that when you call setState() in componentWillMount() , the component will not be rendered again. Therefore, you need to use componentDidMount() . After further reading, I found out that it was fixed in a subsequent release by the React team. Now you can call setState() on componentWillMount() . I think that is why everyone recommends making AJAX calls in didMount .

One of the comments also expresses my thoughts very artistically -

well, you are not calling setState from componentWillMount, nor componentDidMount directly, but from the new asynchronous stack. I have no idea how to react accurately in order to maintain a link to this using live event listeners from different methods. when using undocumented functions, they’re not scary enough for you and want a little excitement so that it can work and maybe even in future versions, then don’t be shy, I don’t know if it will break or not

+17
source

All Articles