gpt4 book ai didi

reactjs - React - 如何检测父组件的所有子组件何时对用户可见?

转载 作者:行者123 更新时间:2023-12-03 13:19:04 24 4
gpt4 key购买 nike

TL;DR

How can a parent component know when the rendering of every child component under it has finished and the DOM visible to the user with its most up to date version?

假设我有一个组件 A,它有一个由 3x3 孙组件组成的子 Grid 组件。这些孙组件中的每一个都从 Restful API 端点获取数据,并在数据可用时呈现自身。

我想用 loader 占位符覆盖 Component A 的整个区域,仅当网格中的最后一个组件获取数据时才会显示成功并渲染它,这样它就已经在 DOM 上并且可以查看了。

用户体验应该是从“加载器”到完全填充的网格的 super 平滑过渡,而不会闪烁。

我的问题是确切地知道何时在加载器下揭开组件。

有什么机制可以让我绝对准确地做到这一点吗?我不会为加载程序硬编码时间限制。据我了解,对每个子组件依赖 ComponentDidMount 也是不可靠的,因为它实际上并不能保证组件在调用时对用户完全可见。

进一步提炼问题:

I have a component that renders some kind of data. After it's initialized it doesn't have it, so in its componentDidMount it hits an API endpoint for it. Once it receives the data, it's changing its state to reflect it. This understandably causes a re-render of the final state of that component. My question is this: How do I know when that re-render has taken place and is reflected in the User facing DOM. That point in time != the point in time when the component's state has changed to contain data.

最佳答案

React 中有两个生命周期钩子(Hook),它们在组件的 DOM 渲染后被调用:

对于您的用例,当N个子组件各自满足某些条件X时,您的父组件P感兴趣。 X可以定义为一个序列:

  • 异步操作完成
  • 组件已渲染

通过组合组件的状态并使用 componentDidUpdate Hook ,您可以知道序列何时完成以及您的组件何时满足条件 X。

您可以通过设置状态变量来跟踪异步操作何时完成。例如:

this.setState({isFetched: true})

设置状态后,React 将调用您的组件 componentDidUpdate 函数。通过比较此函数中的当前和先前状态对象,您可以向父组件发出信号,表明您的异步操作已完成并且新组件的状态已呈现:

componentDidUpdate(_prevProps, prevState) {
if (this.state.isFetched === true && this.state.isFetched !== prevState.isFetched) {
this.props.componentHasMeaningfullyUpdated()
}
}

在 P 组件中,您可以使用计数器来跟踪有多少子组件进行了有意义的更新:

function onComponentHasMeaningfullyUpdated() {
this.setState({counter: this.state.counter + 1})
}

最后,通过了解 N 的长度,您可以知道何时发生所有有意义的更新,并在 P 的渲染方法中采取相应的操作:

const childRenderingFinished = this.state.counter >= N

关于reactjs - React - 如何检测父组件的所有子组件何时对用户可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com