【问题标题】:Get notified when React tree is updatedReact 树更新时收到通知
【发布时间】:2019-12-07 14:20:13
【问题描述】:

ReactDOM.render 接受一个可选的回调,该回调在组件渲染时执行:

ReactDOM.render(element, container[, callback])

React/ReactDOM 中是否有类似的回调,当从内部更新树中的组件(任何深度)时执行,即使用 setState?


  • 仅在根组件上提供 componentDidUpdate 是行不通的,因为子更新不会触发该方法:https://codesandbox.io/s/react-example-yjq0r
  • 可以使用 MutationObserver 订阅 DOM 树更新,但我想知道 React 是否提供了开箱即用的功能。

【问题讨论】:

  • componentDidUpdate 怎么样?
  • setState(updater[, callback]) setState 也接受callback
  • 是的,componentDidUpdate/setState 回调,但针对整个树。

标签: javascript reactjs


【解决方案1】:

这可以使用React.Profiler

<React.Profiler id="app" onRender={callback}>
  <Root />
</React.Profiler>

https://codesandbox.io/s/react-example-lmvzk

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 2021-07-30
    相关资源
    最近更新 更多