如何在将props传递回父组件时触发useEffect



这个问题是针对React Native应用程序中的React Navigation 5 .当将一个props传递回父屏幕时,如何在父屏幕中为useEffect设置触发器?下面是一个例子:

Child Screen
_onPress = (country, country_code, calling_code) => {
const { navigation, route } = this.props;
navigation.navigate("parent"
{select:{
country_name: country,
country_code: country_code,
calling_code: calling_code
});
};

在父组件上。useEffect用于在道具select从子屏幕传递回来后做一些事情:

useEffect(()=> {
if (route.params?.select?) {
//do something after select is passed back
}
}, [what is the trigger?])  //<<==how to setup trigger for useEffect?. [] did not work.

如何在父组件中为useEffect设置触发器?尝试使用[],这将触发任何重新加载,但它没有工作。相同的道具select是否从父组件传递到子屏幕,在子屏幕更新后再传递回父组件?select是触发器吗?

既然你使用的是React Navigation 5,你能做的就是用useFocusEffect代替useEffect,你的函数将在每次用户到达/返回父屏幕时被调用。

首先在文件的顶部导入useFocusEffect,如下所示:

import { useFocusEffect } from "@react-navigation/native"

然后用useFocusEffect替换useEffect,像这样:

useFocusEffect(
React.useCallback(() => {
if (route.params?.select?) {
//do something after select is passed back
}
return () => {
// Here you can do something when the screen is unfocused such as clearing event listners but you can also leave it empty if you want

};
}, [])
);

当您从父屏幕移动到子屏幕时,您还可以像这样设置导航状态参数。

props.navigation.navigate('ChildScreen', {onNewCreate});

子组件中的

select:{
country_name: country,
country_code: country_code,
calling_code: calling_code
}

props.navigation.state.params.onNewCreate(select);

在父组件中定义onNewCreate(),你可以做你想做的。

const onNewCreate = async (select) => {
//You can do what you want here with select}