[英]Using React, how do you pass a function from a parent component to a child component and run it in the useEffect hook?
I'm using React to pass a function from a parent component to a child component and trying to run it in the useEffect()
hook.我正在使用 React 将 function 从父组件传递给子组件,并尝试在
useEffect()
挂钩中运行它。
Parent家长
function Parent(props) {
function alertMe() {
alert('me');
}
render (
<div>
<Child alertMe={alertMe} />
</div>
);
}
Child孩子
function Child(props) {
const { alertMe } = props;
useEffect(() => {
alertMe();
}, [alertMe]);
render (
<div>
// stuff
</div>
);
}
If I remove alertMe
as a dependency in the useEffect()
of the Child component, it only fires once, but I get a warning:如果我将
alertMe
作为子组件的useEffect()
中的依赖项删除,它只会触发一次,但我会收到警告:
React Hook useEffect has missing dependencies: 'alertMe'.
React Hook useEffect 缺少依赖项:'alertMe'。 Either include it or remove the dependency array react-hooks/exhaustive-deps
要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps
The alertMe
function is defined once in the Parent component on load, so I don't understand why it would run endlessly in the Child component. alertMe
function 在加载时在父组件中定义一次,所以我不明白为什么它会在子组件中无休止地运行。 It's not changing like state.它不会像 state 那样改变。
How can I add alertMe
as a useEffect()
dependency but still only run it once?如何将
alertMe
添加为useEffect()
依赖项但仍只运行一次?
See, your Parent
re-declares alertMe
each time it's re-rendered.看,每次重新渲染时,您的
Parent
都会重新声明alertMe
。 And since alertMe
is referentially different useEffect
in Child
will detect that and re-run.并且由于
alertMe
在Child
中引用不同的useEffect
将检测到并重新运行。
Better not fighting with useEffect
's dependencies(they are for a reason.).最好不要与
useEffect
的依赖关系作斗争(它们是有原因的。)。 Let's ensure your alertMe
is referentially the same:让我们确保您的
alertMe
在引用上是相同的:
function Parent(props) {
const alertMe = useCallback(() => {
alert('me');
});
render (
<div>
<Child alertMe={alertMe} />
</div>
);
}
Think about useEffect
with dependencies list as about componentDidUpdate
in hooks' world.将带有依赖项列表的
useEffect
视为钩子世界中的componentDidUpdate
。 Better keep component in sync with props than ignore changes outside.最好让组件与 props 保持同步,而不是忽略外部的变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.