问题描述
整个React DOM树加载完毕后,如何触发动作?
就像知道孩子的兄弟姐妹何时被装载一样。
我相信componentDidUpdate
容器组件的情况应该只是一个火的时候,它完全呈现(作为其子组件已经渲染),但我发现,情况并非如此。
例如:
class ParentContainer extends Component {
componentDidUpdate() {
// all of the children should be rendered by now?
const { section } = this.props
const scrollToEl = document.getElementById(section)
if (scrollToEl) {
scrollToEl.scrollIntoView({block: 'start', behavior: 'smooth'})
}
}
render() {
return (
<div>
<SiblingWithChildren1 />
<SiblingWithChildren2 />
<Child1>
<Child2>
array.map(comp =>
<Section id={comp.id} />
)
</Child2>
</Child1>
</div>
)
}
}
在这种情况下,文档开始滚动到可能与Section
ID相匹配的元素。
但是,滚动显示得很短,因为所有内容还没有完全在DOM中呈现,即使只是几毫秒。
如果SiblingWithChildren
组件尚未完全加载,则将抛出文档的高度。
使用setTimeout
似乎很脆弱。
1楼
componentDidUpdate
仅在更新时触发。
在初始加载时,您需要componentDidMount
。
是React组件生命周期的文档。