componentDidMount() is not getting called but only in a particular circumstance

僤鯓⒐⒋嵵緔 提交于 2019-12-04 06:23:04

It's been more than a week I've been banging my head against the wall on this issue and it's finally solved. Admittedly, lots of concepts that I thought I understood became even clearer in the process.

The error was due a logical error on my part that handled "isLoading" animation logic -- yes, as simple and stupid as that!!!

What I really wanted to share here are the lessons I've learned for everyone who may experience a similar behavior in the future.

  1. You should hit componentDidMount() every time you load your component. Even if you go back and forth to load the same component. But you hit componentDidMount() ONLY IF your component was unmounted in the first place. If the component does not get unmounted, you will NOT hit componentDidMount() in your subsequent uses of the component. So look at your logic carefully to see if your component gets unmounted if you navigate away from it. I think the easiest way to see if this is happening is by adding componentWillUnmount() method with a debugger in it. If you're hitting this method when you navigate away from your component, that means it is unmounting.
  2. Did lots of research during this process to see where the best place to make API calls to fetch data and it's definitely clear that componentDidMount() is still the best place to do it. Having said that you may need additional logic in your componentDidMount() to make sure you don't make any unnecessary API calls because your data may still be in your store.
  3. During my research, some suggested that it's better to use componentWillReceiveProps() method to make my API call to fetch data. This is bad advice! As a matter of fact, componentWillReceiveProps(), componentWillUpdate() and componentWillMount() methods are being deprecated so we should not use them for two reasons: future compatibility and following best practices. Here's more info on why they're being deprecated: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
  4. Maybe the most important lesson is this: the cause of the problem may be much simpler than you think -- it usually is -- and the logic in your code may be the cause of the issue -- it usually is!

Hope these lessons will help others find their solutions quickly and painlessly!

ComponentDidMount it's called just one time, when the component is mounted. As you are using a prop to then make an api call, I would use componentWillReceiveProps and check props and then make an api call.

If you want yo check that the componentDidMount is used by your flow, use a console.log to check it.

Regards!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!