When does a component unmount?

前端 未结 4 539
感动是毒
感动是毒 2020-12-25 09:52

My current understanding is that a component mounts onto the DOM when it is needed to be seen or when the route requires that component. It will also render its child compon

4条回答
  •  Happy的楠姐
    2020-12-25 10:41

    Simply put, when a component has mounted, componentDidMount() is called, when the component is about to unmount, componentWillUnmount() is called. During re-rendering, if the component is neither to be mounted nor unmounted, neither of the aforementioned methods will be called. Instead, simply the changes made to the code of the component will be updated.

    Please remember that most React apps are Single Page Apps which means they only update the existing page, they don't create any new page like page1.html, page2.html. What happens is that React unmounts unnecessary components from page1 and mounts necessary components described in page2 such that it looks like page2. But it doesn't really "leave page1.html" and take you to a whole new page called page2.html. All it does is simply pop and push components in one canvas or page. In other words, React "brings" page2 into page1. But the canvas remains the same(page1).

    So, the answer to your question is, yes, a component will unmount and remount when its removed or added to the page.

提交回复
热议问题