![](/img/trans.png)
[英]pass setState from parent to its child component using React Hook
[英]Using React, how do you pass a function from a parent component to a child component and run it in the useEffect hook?
我正在使用 React 将 function 从父组件传递给子组件,并尝试在useEffect()
挂钩中运行它。
家长
function Parent(props) {
function alertMe() {
alert('me');
}
render (
<div>
<Child alertMe={alertMe} />
</div>
);
}
孩子
function Child(props) {
const { alertMe } = props;
useEffect(() => {
alertMe();
}, [alertMe]);
render (
<div>
// stuff
</div>
);
}
如果我将alertMe
作为子组件的useEffect()
中的依赖项删除,它只会触发一次,但我会收到警告:
React Hook useEffect 缺少依赖项:'alertMe'。 要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps
alertMe
function 在加载时在父组件中定义一次,所以我不明白为什么它会在子组件中无休止地运行。 它不会像 state 那样改变。
如何将alertMe
添加为useEffect()
依赖项但仍只运行一次?
看,每次重新渲染时,您的Parent
都会重新声明alertMe
。 并且由于alertMe
在Child
中引用不同的useEffect
将检测到并重新运行。
最好不要与useEffect
的依赖关系作斗争(它们是有原因的。)。 让我们确保您的alertMe
在引用上是相同的:
function Parent(props) {
const alertMe = useCallback(() => {
alert('me');
});
render (
<div>
<Child alertMe={alertMe} />
</div>
);
}
将带有依赖项列表的useEffect
视为钩子世界中的componentDidUpdate
。 最好让组件与 props 保持同步,而不是忽略外部的变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.