如何在createSwitchNavigator中使用Redux?

时间:2018-10-15 07:13:53

标签: react-native redux navigation state-management

我正在尝试将开关导航器与redux一起使用。以下是我的代码。

import { createSwitchNavigator, createStackNavigator } from 'react-navigation';
import LoginScreen from '../screens/LoginScreen';
import EmployeeListScreen from '../screens/EmployeeListScreen';
import DetailsView from '../screens/EmployeeDetailViewScreen';
import EmployeeForm from '../screens/EmployeeForm';
import AuthLoadingScreen from "../screens/AuthLoadingScreen.js";
import {connect  } from "react-redux";
import { AppNavigator } from "../navigations/AppNavigator.js";

const AppStack = createStackNavigator({ 
    List:{screen:EmployeeListScreen},
    Detail:{screen:DetailsView},
    Form:{screen:EmployeeForm}
 });
const AuthStack = createStackNavigator({ Login: LoginScreen });

export const AuthNavigator = createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    App: AppNavigator,
    Auth: AuthStack,
  },
  {
    initialRouteName: 'AuthLoading',
  }
);

const AuthWithNavigationState = ({ dispatch, nav }) => (
    <AuthNavigator  />
  );

  const mapStateToProps = state => ({
    nav: state.nav,
  });

  export default connect(mapStateToProps)(AuthWithNavigationState);

我正在导入此组件是我的App.js文件,并按以下方式使用它与redux存储区连接,但它给我的错误是,未定义React,错误位于connect(AuthWithNavigationState)

import React from 'react';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware  } from 'redux';
import thunk from 'redux-thunk';
import AppReducer from './src/reducers/AppReducer';
import AuthWithNavigationState from './src/navigations/AuthNavigator.js';

const store = createStore(AppReducer,applyMiddleware(thunk));

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

我尝试遵循下面链接的说明,但仍然遇到相同的错误。

how can i integrate redux store to react native?

谁能告诉我我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

经过过多尝试,我发现,切换导航器不需要连接到商店,因此以下步骤不正确。

const AuthWithNavigationState = ({ dispatch, nav }) => (
    <AuthNavigator  />
  );

  const mapStateToProps = state => ({
    nav: state.nav,
  });

  export default connect(mapStateToProps)(AuthWithNavigationState);

我只是导出了AuthNavigator,然后将其导入了App.js,这对我有用。

import React from 'react';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware  } from 'redux';
import thunk from 'redux-thunk';
import AppReducer from './src/reducers/AppReducer';
import AuthNavigatorfrom './src/navigations/AuthNavigator.js';

const store = createStore(AppReducer,applyMiddleware(thunk));

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