当前位置: 代码迷 >> JavaScript >> 加载整个React dom树后采取行动
  详细解决方案

加载整个React dom树后采取行动

热度:100   发布时间:2023-06-13 11:45:12.0

整个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似乎很脆弱。

componentDidUpdate仅在更新时触发。

在初始加载时,您需要componentDidMount

是React组件生命周期的文档。

  相关解决方案