Why componentDidMount gets called multiple times in react.js & redux?

前端 未结 1 554
慢半拍i
慢半拍i 2021-02-01 01:56

I read componentDidMount gets called only once for initial rendering but I\'m seeing it\'s getting rendered multiple times.

It seems I created a recursive l

相关标签:
1条回答
  • 2021-02-01 02:38

    A component instance will only get mounted once and unmounted when it gets deleted. In your case it gets deleted and recreated.

    The point of the key prop is to help React find the previous version of the same component. That way it can update a previous component with new props rather than create a new one.

    React can often work fine without a key, the exception being a list with items. It wants a key there so it can keep track when items get rearranged, created or deleted.

    In your case, you are explicitly telling React that your component is different from the previous one. You're giving a new key on each render. This forces React to treat the previous instance as having been deleted. Any children of that component are also unmounted and dismantled.

    What you ought to do is not (ever) generate a key at random. Keys should always be based on the identity of the data a component is displaying. If it's not a list item you probably don't need a key. If it is a list item, it's much better to use a key derived from the data's identity, such as an ID property, or maybe a combination of multiple fields.

    If generating a random key would have been the correct thing to do, React would have just taken care of that for you.

    You should place your initial fetch code in the root of your React tree, usually that's App. Don't put it in some random child. At least you should put it in a component that exist for the lifetime of your app.

    The main reason to put it in componentDidMount is so it doesn't run on the server, because server-side components never get mounted. This is important for universal rendering. Even if you're not doing this now, you might do this later, and being prepared for it is a best practice.

    0 讨论(0)
提交回复
热议问题