React Native navigation.navigate 参数未更新 [英] React Native navigation.navigate params not updating

查看:157
本文介绍了React Native navigation.navigate 参数未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 navigation.navigate() 从主屏幕导航到详细信息屏幕.当我第一次单击按钮导航时它工作正常,但之后当我从细节返回主页并单击另一个项目以查看细节时,细节屏幕上的参数没有改变(它仍然是第一次点击的参数).这是我的代码:

I try to navigate from home screen to detail screen using navigation.navigate(). When the first time i click button to navigate it works fine, but after that when i go back from detail to home and click another item to see the detail, the params on detail screen is not changed (its still the params of the 1st click). Here my code :

<TouchableNativeFeedback
  key={index}
  onPress={() => {
    navigation.navigate('PenghuniScreen', {
      screen: 'DetailPenghuni',
      params: {
        penghuni: item,
      },
    });
  }}></TouchableNativeFeedback>;

item 是来自 map loop 的对象.我尝试使用反应导航 usefocuseffect 控制台日志,并且第一次点击后参数不会改变.

item is object from map loop . i try to console log using react navigation usefocuseffect and the params not changin after 1st click.

useFocusEffect(
    React.useCallback(() => {
      console.log('My params:', route.params.penghuni);
      setPenghuni(route.params.penghuni);
      return () => {
        // source.cancel('Api Canceled');
        console.log('tutup detail penghuni');
      };
    }, []),
  );

有人对此有解决方案吗?

anyone got solution for this?

推荐答案

您忘记将 route 依赖项添加到您的 useCallback,因此它正在获取旧值.

You forgot to add the route dependency to your useCallback, so it is getting the old value.

尝试添加[route]:

React.useCallback(() => {
      console.log('My params:', route.params.penghuni);
      setPenghuni(route.params.penghuni);
      return () => {
        // source.cancel('Api Canceled');
        console.log('tutup detail penghuni');
      };
}, [route]), 

我建议你为你的项目添加

I suggest you adding the eslint for hooks to your project, to detect missing dependecies.

观察:为什么不通过导航参数传递这些值而不是使用useFocusEffect?

Observation: Why don't you pass these values though the navigation params instead of using useFocusEffect?

navigation.navigate('DetailPenghuni', { penghuni: item1 }) // item1 press 
navigation.navigate('DetailPenghuni', { penghuni: item2 }) // item2 press

如果您需要取消某些内容,您可以随时使用 关闭屏幕时自动调用 useEffect clean 回调.

If you need to cancel something you can always use the useEffect clean callback called automatically when you close a screen.

这篇关于React Native navigation.navigate 参数未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆