How to get access to reducer inside App using React Navigation v5 in React Native?

眉间皱痕 提交于 2020-03-05 00:21:34

问题


I'm trying to build app with React Navigation v5 and stuck with Authentication flow. Here is some code to understand what I'm trying to do:

const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const AuthContext = React.createContext();

export default class App extends Component {
  // constructor() ...

render() {
  const store = configureStore(); // rootReducer

  return (
    <AuthContext.Provider store={store}>
      <NavigationContainer>
        // here I have to access my userReducer to check is user logged in and using LoginStack or Drawer
)
        // my stacks
}

So in React Navigation docs Authentication flows uses function components and React Hooks inside them. But I'm using class-component, and I have my reducer in standalone file. I tried to use connect() as I always do on child components in my app, but this won't work.

So is there any way to access (or map) reducer to App at the topmost level? Or maybe I'm doing something wrong and there is a better way to build switch between 2 separate stacks based on authentication?


回答1:


Im not sure if this is the best way but you'll just have to use react hooks and redux subscribe:

export default function Navigation({store}) {

  const [authorized, setAuthorized] = useState(
    store.getState().user.auth !== null,
  );

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setAuthorized(store.getState().user.auth !== null);
    });

    return () => { unsubscribe(); }
  });

  return (
    <NavigationContainer>
      {authorized ?
        <Stack.Navigator>...</Stack.Navigator> : <Stack.Navigator>...</Stack.Navigator>}
    </NavigationContainer>
  )
}

Then pass your store:

export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Navigation store={store} />
      </Provider>
    );
  }
}


来源:https://stackoverflow.com/questions/60217674/how-to-get-access-to-reducer-inside-app-using-react-navigation-v5-in-react-nativ

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