[英]Detect when any part of component tree has changed in React
I have two components, Parent
and Child
:我有两个组件,
Parent
和Child
:
function Child() {
const [counter, setCounter] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => setCounter(counter + 1), 1000);
return () => clearInterval(interval);
}, [counter, setCounter]);
return <div>{counter}</div>;
}
function Parent() {
return <Child />;
}
Child
is just a simple timer that increments/renders a counter. Child
只是一个简单的计时器,它增加/呈现一个计数器。
From Parent
( ie my root component), how can I know when any part of the component tree has changed?从
Parent
(即我的根组件),我怎么知道组件树的任何部分何时发生了变化? For example, when Child
updates its state and re-renders?例如,当
Child
更新其 state 并重新渲染时?
Passing a callback to Child
is not a solution, because in a real app, I would have hundreds of children, and I need to know any time any part of the component tree changes.将回调传递给
Child
不是解决方案,因为在一个真实的应用程序中,我会有数百个孩子,并且我需要随时知道组件树的任何部分发生变化。
I tried using useEffect
/ componentDidUpdate
in Parent
, but that doesn't get called when a child managing its own state re-renders.我尝试在
Parent
中使用useEffect
/ componentDidUpdate
,但是当管理自己的 state 的孩子重新渲染时,它不会被调用。 Is there a way to achieve what I want?有没有办法实现我想要的?
It looks like a Redux use case.它看起来像一个 Redux 用例。 You can achieve this easily on redux.
您可以在 redux 上轻松实现这一点。
I think what you should try doing is have each component be able to know if the current render cycle will cause a DOM change, based on whatever props or state have changed.我认为您应该尝试做的是让每个组件能够知道当前渲染周期是否会导致 DOM 更改,基于任何道具或 state 已更改。 Then call a function provided through Context (a provider in the component that wants to know about the changes, a subscriber in each child) to let the parent know a change has happened.
然后调用通过Context提供的 function(组件中想要了解更改的提供者,每个子项中的订阅者),让父级知道发生了更改。 You can call this function in a
useEffect
so that it happens after the DOM changes.您可以在 useEffect 中调用此
useEffect
以便它在 DOM 更改后发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.