【问题标题】:How to trigger useEffect when passing props back to parent component将道具传回父组件时如何触发useEffect
【发布时间】:2021-06-06 02:48:11
【问题描述】:

这个问题是针对 React Native 应用程序中的 React Navigation 5 的。将道具传回父屏幕时,如何在父屏幕中为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 用于在子屏传回 props 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 设置触发器?尝试使用 [] 将触发任何重新加载,但它没有工作。相同的 props select 是否应该从父组件传递到子屏幕并在子屏幕更新后再次传递回父组件? select 是触发器吗?

【问题讨论】:

    标签: react-navigation react-navigation-v5


    【解决方案1】:

    好吧,既然您使用的是 React Navigation 5,您可以做的是将 useEffect 替换为 useFocusEffect,并且每次用户到达/返回父屏幕时都会调用您的函数。

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

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

    然后将 useEffect 替换为 useFocusEffect,如下所示:

     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
           
          };
        }, [])
      );

    【讨论】:

      【解决方案2】:

      当您像这样从父屏幕移动到子屏幕时,您可以做的另一件事是设置导航状态参数。

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

      在刚刚调用this的子组件中

      select:{
          country_name: country,
          country_code: country_code,
          calling_code: calling_code
      }
      
      
       props.navigation.state.params.onNewCreate(select);
      

      在 Parent 组件中只需定义 onNewCreate() ,你就可以做你想做的事了。

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

      【讨论】:

      • 这是正在使用的模式,它会在反应导航 5.x 中引起警告。
      猜你喜欢
      • 2021-01-16
      • 2022-06-14
      • 1970-01-01
      • 2021-02-07
      • 2020-09-07
      • 1970-01-01
      • 2020-07-30
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多