何时卸下组件? [英] When does a component unmount?

查看:32
本文介绍了何时卸下组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的理解是,当需要查看组件或路由需要该组件时,会将组件安装到DOM上.它还将渲染其子组件.这是否意味着当您访问没有该组件的路线时,或者当您访问任何未显示该组件产生的元素的页面时,该组件将被卸载?这样,每次在DOM中显示组件时(在prop和状态更改之外)都需要重新安装组件,对吗?

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 components. Does this mean that a component will be unmounted when you visit a route that doesn't have that component or whenever you visit any page that doesn't show the element that component produces? Thus, a component will need to be remounted every time it shows up on the DOM (outside of prop and state changes), correct?

推荐答案

VirtualDOM对帐期间,如果存在某个组件但不再存在该组件,则认为该组件已卸载并且有机会清理(通过 componentWillUnmount ).

During the VirtualDOM Reconciliation if a component existed but no longer will, the component is considered unmounted and given a chance to clean up (via componentWillUnmount).

相反,在对帐过程中,如果某个组件不存在,但现在已经存在,则认为该组件已准备好安装,并有机会进行自我准备( constructor / componentWillMount )

The reverse is true, during the reconciliation, if a component didn't exist, but now does, the component is considered ready to mount, and given a chance to prep itself (constructor / componentWillMount)

当拆除一棵树时,旧的DOM节点将被破坏.成分实例接收componentWillUnmount().建一棵新树时,新的DOM节点将插入到DOM中.组件实例接收componentWillMount(),然后是componentDidMount().任何状态与那棵​​老树相关联的东西丢失了.

When tearing down a tree, old DOM nodes are destroyed. Component instances receive componentWillUnmount(). When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive componentWillMount() and then componentDidMount(). Any state associated with the old tree is lost.

https://facebook.github.io/react/docs/reconciliation.html

如果您还没有阅读过该特定页面,则非常值得一读.它还说明了为什么 key 对于重复的元素非常重要.

That particular page is well worth a read if you haven't already. It also explains why key is pretty important for repeated elements.

这篇关于何时卸下组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆