React native navigation 5 passing updated component

不问归期 提交于 2021-02-15 07:51:26

问题


I am new to react native and its navigation modules. I have a simple dashboard.js file where I am using tab navigator like this -

 <Tabs.Navigator tabBarOptions={{ activeTintColor: '#ff5757' }}>
    <Tabs.Screen
       options={{
       tabBarIcon: ({ color }) => 
        <Icon name='star-border' size={30} padding={15} color={color} />,}}
        name={'Orders'}
        component={Order}
        initialParams={{user}}
   />
<Tabs.Screen
component= {AnotherComponent}
/>

As you can see I am passing InitialParams where I have user props. And I can easily get it in Order component by route.params.

However, in my dashboard component I also have a method that runs every 1 minute and updates user props.

I can't get the updated value of user props in Order component. I am stuck with this for 2 days. In the past I have done like this -

<Tabs.Screen
component = {() => <SomeComponent props= {props}/>}

And it worked fine. But with react-navigation 5 its not working any more.

Please help me if anyone knows. plz.

Thanks a lot.


回答1:


The initial props seems to be a constant also as per the documentation you have to use redux or context api to update the badge counts in the tabs so I think it will be better to take that approach to handle this problem. Came up with a count changing scenario just like yours using context API.

const CountContext = React.createContext(0);

function HomeScreen() {
  return (
    <View>
      <CountContext.Consumer>
        {value => <Text>Home! {value}</Text>}
      </CountContext.Consumer>
    </View>
  );
}

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

  return (
    <CountContext.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>
    </CountContext.Provider>
  );
};

This way you can skip the navigation params and directly send data to the tab, and this data can be read from other tabs or somewhere down the tree as well.

You can check the full snack here https://snack.expo.io/@guruparan/5c2b97



来源:https://stackoverflow.com/questions/61913658/react-native-navigation-5-passing-updated-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!