简体   繁体   English

父组件内的 React useEffect 不会通过子组件内的更改重新呈现

[英]React useEffect inside parent component doesnt rerender by changes inside child

I have App component which returns only a react component called Home.我有 App 组件,它只返回一个名为 Home 的反应组件。 Inside App component, I have a useEffect which has no dependancy, in order to trigger any changes.在 App 组件内部,我有一个没有依赖关系的useEffect ,以触发任何更改。 I expect the App useEffect to rerender when something changes in the home component, but this doesnt happen.我希望 App useEffect 在主组件发生更改时重新呈现,但这不会发生。 Doesnt react support such thing?反应不支持这样的事情吗?

This is not supported out of the box.开箱即用不支持此功能。 The child will rerender when parent rerenders but not the other way around.当父级重新渲染时,子级将重新渲染,但反之则不然。

If every parent rerenders when a child rerender, then even a tiny button state change will cause the whole tree to rerender.如果每个父级都在子级重新渲染时重新渲染,那么即使是一个很小的按钮 state 更改也会导致整个树重新渲染。

You have callbacks that can help you get around this.您有可以帮助您解决此问题的回调。 The child should be passed a callback function as a prop.孩子应该通过一个回调 function 作为道具。 Inside this callback function body the parent state will be updated.在此回调 function 主体内,父 state 将被更新。 So now when this function runs (from within the child).所以现在当这个 function 运行时(从孩子内部)。 The parent also rerenders.父级也重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM