反应导航:如何根据条件设置屏幕的初始参数?

问题描述 投票:0回答:2

我将BottomTabsNavigator作为StackNavigator的一部分。

启动应用程序时,需要根据initialParams中的条件在“主页”选项卡中通过BottomTabsNavigator

显然,BottomTabsNavigator仅渲染一次,并且initialParams总是根据条件发送默认值,而不是新值。

  <Tab.Screen
    name="Home"
    component={HomeScreen}
    options={{
      title: 'Home',
      tabBarIcon: 'home-outline',
      tabBarLabel: 'Home',
    }}

    initialParams={{ 'tappedNotification1': notificationOpened }} // <---- here I want to send notificationOpened  value when its value is updated, 
  />

我使用下面的钩子将notificationOpened的值更新为true(对于主屏幕,它需要作为initialParams发送。

    function onOpened(openResult) {
      navigation.navigate('NotificationDetailsScreen', {
        ...openResult.notification.payload.additionalData,
        tappedNotification: true,
        isRead: false,
      });

      setNotificationOpened(true);
    }
    OneSignal.addEventListener('opened', onOpened);

    return () => {
      OneSignal.removeEventListener('opened', onOpened);
    }; // unsubscribe on unmount
  }, [navigation, user]);
javascript react-native react-navigation
2个回答
0
投票

您可以将notificationOpened用作route.params中的参数。我不知道您的HomeScreen,但我为您编写了示例。希望对您有帮助

function HomeScreen(props) {
  const { route } = props
  const { notificationOpened } = route.params

  function onOpened(openResult) {
      navigation.navigate('NotificationDetailsScreen', {
        ...openResult.notification.payload.additionalData,
        tappedNotification: true,
        isRead: false,
      });

      setNotificationOpened(true);
    }
    OneSignal.addEventListener('opened', onOpened);

    return () => {
      OneSignal.removeEventListener('opened', onOpened);
    }; // unsubscribe on unmount
  }, [navigation, user]);
};

0
投票

官方文档建议使用上下文或类似redux的某种存储来更新选项卡上的计数变量。您有类似的要求。您可以查看此示例以了解执行此操作的想法。

首先,您需要创建一个上下文文件

const NotificationContext = React.createContext(0);

export default NotificationContext;

以及包含选项卡的文件

const MyTabs = () => {
  const [count, setCount] = React.useState(0);

  return (
    <NotificationContext.Provider value={count}>
      <View style={{ flex: 1 }}>
        <Text>{count}</Text>
        <Button title="count" onPress={() => setCount(count + 1)} />
        <Tab.Navigator>
          <Tab.Screen name="Home" component={HomeScreen} options={{ title: 'My home' }}/>
          <Tab.Screen name="Settings" component={SettingsScreen} options={{ title: 'My home 2' }}/>
        </Tab.Navigator>
      </View>
    </NotificationContext.Provider>
  );
};

主屏幕文件可以使用'usecontext'进行读取和更新。>

import NotificationContext from './NotificationContext';

export function HomeScreen() {
  const count = React.useContext(NotificationContext);
  return (
    <View>
      <Text>{count}</Text>
    </View>
  );
}

此示例基于您提供的小吃。https://snack.expo.io/@guruparan/tabs-with-context

© www.soinside.com 2019 - 2024. All rights reserved.