简体   繁体   English

在子组件的useEffect之前触发父组件的useEffect

[英]Triggering parent component's useEffect before child component's useEffect

I am currently implementing metrics/analytics in a React application and I am trying to log pages in the order they are opened (related) .我目前正在 React 应用程序中实施指标/分析,并且我正在尝试按照页面打开的顺序记录页面(相关) I have a certain page eg ParentComponent and I have embedded there-in, child component eg ChildComponent.我有一个特定的页面,例如 ParentComponent,我已经在其中嵌入了子组件,例如 ChildComponent。

const ParentComponent = () => {
   // log page using useEffect
   return (<ChildComponent />)
}

const ChildComponent = () => {
   // log page using useEffect
   // return something else 
}

Both components have useEffects eg两个组件都有 useEffects 例如

useEffect(() => {
   // log page e.g ParentComponent or ChildComponent.
}, []);

However, I notice every-time that the child's useEffect is called before the parent's.但是,我每次都注意到孩子的 useEffect 在父母之前被调用。 My understanding is that this is understandable as the child is rendered fully before the parent is.我的理解是,这是可以理解的,因为孩子在父母之前被完全渲染。 But I please need to know if there are any ways of ensuring I can call functionality in the parent's first of all before calling functionality in the child's?但是我需要知道是否有任何方法可以确保我可以在调用孩子的功能之前首先调用父母的功能?

Thanks.谢谢。

The behavior your are intending with useEffect is not possible.您打算使用useEffect的行为是不可能的。 Here is a possible workaround:这是一个可能的解决方法:

 function App() { return( <ParentPage/> ); } function ParentPage() { const logParent = React.useCallback(() => { console.log("Logging ParentPage..."); },[]); return( <React.Fragment> <div>I am ParentPage...</div> <ChildPage logParent={logParent} /> </React.Fragment> ); } function ChildPage(props) { React.useEffect(() => { if (props.logParent) { props.logParent(); } console.log("Logging ChildPage..."); },[]); return( <div>I am ChildPage...</div> ); } ReactDOM.render(<App/>, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="root"/>

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

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