首页 > 解决方案 > 如何在反应原生导航 v5 中将数据传递回上一个屏幕?

问题描述

我刚刚更新以响应本机导航版本 5。现在我正在尝试在 goBack() 调用上将数据发送回上一个屏幕。

我推下一个视图

const onSelectCountry = item => {
    console.log(item);
};

navigation.navigate('SelectionScreen', {
        onSelect: onSelectCountry});

并在通过调用从 FlatList 中选择项目后返回:

function onSelectedItem(item) {
    route.params.onSelect(item);
    navigation.goBack();
}

但是通过使用参数发送函数,我得到一个警告:在导航状态中发现了不可序列化的值......

有人可以告诉我正确的方法吗?

标签: javascripttypescriptreact-nativereact-navigationreact-native-navigation

解决方案


这是一个实现

屏幕A

const Screen1 = ({navigation, route}) => {
  const [item, setItem] = useState(null);

  useEffect(() => {
    navigation.addListener('focus', () => {
      console.log(route.params)
    })
  }, [])  

  const onPress = () => {
    navigation.navigate('Screen2', {onReturn: (item) => {
      setItem(item)
    }})
  }
  return (
    // Components
  )
}

屏幕2:

const Screen2 = ({navigation, route}) => {

  useEffect(() => {
    navigation.addListener('focus', () => {
      console.log(route.params)
    })
  }, [])  

  // back Press
  const onPress = () => {
    route.params.onReturn(item);
    navigation.goBack()
  }

  return (
    // Components
  )
}

推荐阅读