英文:
How, when, and why do we clean up our components in react JavaScript?
问题
我明白我们需要在React中清理组件以防止内存泄漏(可能还有其他原因)。我也明白如何使用comonentWillUnmount
(不再使用)和useEffect
钩子。然而,我的问题是什么,以及为什么(真的为什么)要清理我们的组件。我想要一个详细的答案,请,因为我对这个概念有困难理解。
英文:
I understand that we need to cleanup our components in React to prevent memory leaks (Maybe other reasons as well). I also understand how to use comonentWillUnmount
(don't use anymore), and useEffect
hook. However my question is what, and why (really why) do we clean up our components. I'd like a detailed answer please as I am having issues understanding this concept.
答案1
得分: 5
通常情况下,你根本不需要做任何处理。
对于大多数组件,只需改变状态,然后不渲染它们,它们将被卸载,不会留下任何杂乱。
然而,如果你做了任何不会自动清理的事情,你必须自己清理。这包括不在标准React生命周期内的事情:
- 事件监听器需要被解绑(例如,监听
window
的onScroll
事件以在滚动页面时执行一些特殊操作) - 取消在组件实例化时打开的数据订阅(例如,在打开的网络套接字上监听新的聊天室消息)
- 取消不再需要的定时器或间隔器(例如,每秒更新一次时钟)
这并不是一个详尽无遗的清单,但基本思想是,如果在组件的生命周期中进行了任何与渲染组件和一些props无关的操作,那么在组件卸载时你应该考虑“撤销”这些操作。
英文:
You usually don't need to at all.
For most components, simply changing state and then not rendering them will unmount them with no mess.
However, if you do anything that wont be cleaned up, you have to clean it up yourself. This means things that are outside the standard React lifecycle:
- Event listeners need be un-bound (i.e. listening for
onScroll
ofwindow
to do something fancy when you scroll the page) - Unsubscribe from data subscriptions that were opened when that component was instantiated. (i.e. Listening for new chat room messages on an open web socket)
- Cancel a timeout or interval that is no longer needed. (i.e. update a clock once per second)
This is not an exhaustive list, but the idea is that if you do anything in the lifecycle of your component that is not rendering components with some props, you should probably undo that when the component is unmounted.
答案2
得分: -1
使用组件作为简单的组件,显示提供的 props 数据。让父组件负责数据获取。这将使组件更简单和可读性更高。否则,组件内的代码行数将增加,变得不易阅读。不易阅读的组件对其他开发人员来说难以理解,难以调试。在卸载组件时取消订阅。
英文:
Make the most of the components as dump components. display what ever the data provided as props. Make the parent componets responsible for the data fetching. This will make the components more simpler and highly readable. Otherwise no of lines of codes within the components will increase and become less readable.a less readable components is hard to understand for other developers , hard to debugg . Make unsubscribtions on unmounting the components
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论