Reactjs 使用React,如何将函数从父组件传递到子组件,并在useEffect挂钩中运行它?

Reactjs 使用React,如何将函数从父组件传递到子组件,并在useEffect挂钩中运行它?,reactjs,dependency-injection,use-effect,Reactjs,Dependency Injection,Use Effect,我使用React将函数从父组件传递到子组件,并尝试在useffect()hook中运行它 家长 function Parent(props) { function alertMe() { alert('me'); } render ( <div> <Child alertMe={alertMe} /> </div> ); } 功能父级(道具){ 函数alertMe(){ 警惕(“我”); } 渲染( )

我使用React将函数从父组件传递到子组件,并尝试在
useffect()
hook中运行它

家长

function Parent(props) {

  function alertMe() {
    alert('me');
  }

  render (
    <div>
      <Child alertMe={alertMe} />
    </div>
  );
}
功能父级(道具){
函数alertMe(){
警惕(“我”);
}
渲染(
);
}
儿童

function Child(props) {

  const { alertMe } = props;

  useEffect(() => {
    alertMe();
  }, [alertMe]);

  render (
    <div>
      // stuff
    </div>
  );
}
函数子(道具){
const{alertMe}=props;
useffect(()=>{
alertMe();
},[alertMe]);
渲染(
//东西
);
}
如果我在子组件的
useffect()
中将
alertMe
作为依赖项删除,它只会触发一次,但会收到一条警告:

React Hook useEffect缺少依赖项:“alertMe”。包括它或删除依赖项数组react hooks/dep

alertMe
函数只在加载时的父组件中定义了一次,因此我不明白为什么它会在子组件中无休止地运行。它不会像状态一样改变


如何将
alertMe
添加为
useffect()
依赖项,但仍然只运行一次?

请参见,您的
父项每次重新呈现时都会重新声明
alertMe
。由于
alertMe
Child
中的
useffect
在引用上不同,因此
Child
将检测到该情况并重新运行

最好不要与
useffect
的依赖项打交道(它们是有原因的!)。让我们确保您的
alertMe
在引用上是相同的:

function Parent(props) {

  const alertMe = useCallback(() => {
    alert('me');
  });

  render (
    <div>
      <Child alertMe={alertMe} />
    </div>
  );
}
功能父级(道具){
const alertMe=useCallback(()=>{
警惕(“我”);
});
渲染(
);
}

在hooks的世界中,将依赖项列表的
useffect
看作是关于
componentdiddupdate
。最好使组件与道具保持同步,而不要忽略外部的更改。

将其从
useffect
的第二个参数数组中删除。如果您给useEffect一个空数组作为第二个参数,它将只在装入时运行。@skellertor是的,但我得到了警告。您如何将其他参数传递给alertMe?e、 g.
alertMe(index)}/>
答案取决于这些参数的来源,如果以后可以更改,以及它们是在哪个层定义的-
父级
子级