将 redux 添加到 react-navigation 的最短方法是什么?

What is the shortest way to add redux to react-navigation?

我正在将 redux 集成到我的 react-native 应用程序中。想要引入 Provider 并在其中包裹屏幕。我正在使用这样的结构来注册新屏幕:

Navigation.registerComponent('Login', () => LoginScreen);

正如我在 documentation 中看到的那样,我需要将每个组件包装在 <Provider store={store}>

我只是想知道是否存在另一种方法来执行此操作,因为如果我的应用程序中有 10 个屏幕(例如),我需要将它们包装在提供程序中十次。我会得到重复的代码,但是 htis 不好

您可以尝试在初始时直接将 navigation 添加到您的商店:

HomePage.tsx

interface HomePageProps {
  navigation: {
    navigate: (pathName: string) => void;
  };
}
const HomePage: FunctionComponent<HomePageProps> = (props) => {
    const { navigation } = props;
    initStore(navigation);

Store.ts

export const fetchInitStore = (props: HomePageProps) => {
  const { navigation } = props;

  const action: Actions = {
    type: ActionType.INIT_STORE_STATE,
    payload: {
      Navigation: navigation,
    },
  };
  return action;
};

export const initStore = (props: HomePageProps) => {
  (store.dispatch as ThunkDispatch<State, unknown, Actions>)(fetchInitStore(props));
};

在你的减速器中:

case ActionType.INIT_STORE_STATE:
  return actions.payload;

那你可以在其他情况下使用它:

state.Navigation.navigation.navigate('Login');

您可以通过创建包含所有组件的 AppContainer 组件并将 AppContainer 组件包装在 Provider 中来实现。

import React, { Component } from "react";
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import { Provider as StoreProvider } from "react-redux";

const MainNavigator = createStackNavigator({
 firstcomponentpath: FirstComponent,
 secondcomponentpath: SecondComponent
)}

const AppContainer = createAppContainer(MainNavigator);

export default class App extends Component {
super(props);
this.state = {};
}

render() {
return (
<Provider store={store}>
<AppConatiner />
</Provider>
)}