我目前正在 React 应用程序中实现指标/分析,并且我正在尝试按照页面打开的顺序记录页面 (related) 。我有一个特定的页面,例如 ParentComponent,并且我在其中嵌入了子组件,例如 ChildComponent。
const ParentComponent = () => {
// log page using useEffect
return (<ChildComponent />)
}
const ChildComponent = () => {
// log page using useEffect
// return something else
}
两个组件都有 useEffects 例如
useEffect(() => {
// log page e.g ParentComponent or ChildComponent.
}, []);
但是,我注意到每次子级的 useEffect 都会在父级的 useEffect 之前被调用。我的理解是,这是可以理解的,因为 child 在 parent 之前就已经完全渲染了。但我需要知道是否有任何方法可以确保我可以在调用子函数中的功能之前首先调用父函数中的功能?
谢谢。
最佳答案
您想要使用 useEffect
实现的行为是不可能的。这是一个可能的解决方法:
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"/>
关于reactjs - 在子组件的 useEffect 之前触发父组件的 useEffect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64517050/