react-redux和react-natigation的整合。

依赖包的版本

"react": "16.8.3"
"react-native": "0.59.4"
"react-navigation": "2.18.3"
"react-navigation-redux-helpers": "^2.0.8"
"react-redux": "^7.0.1"
"redux": "^4.0.1"

个别依赖包版本间api存在差异,本文配置的是以上版本。

主要文件代码

  1. 路由配置文件;
import {
    createStackNavigator,
    createSwitchNavigator
} from "react-navigation";
import Welcome from '../pages/Welcome';
import MainNavigator from './mainNavigator';

import {connect} from 'react-redux';
import {createReactNavigationReduxMiddleware, reduxifyNavigator} from 'react-navigation-redux-helpers';

export const rootNav = 'AppNavigator';//设置根路由,值要在下面RootNavigator配置中找到

const InitNavigator = createStackNavigator({
    WelcomePage: {
        screen: Welcome,
        navigationOptions: {
            header: null
        }
    }
});
const AppNavigator = createStackNavigator({
    Main: {
        screen: MainNavigator
    }
});
export const RootNavigator = createSwitchNavigator({
        AppNavigator,
        InitNavigator
    }, {
        navigationOptions: {
          title: '今日头条'
        }
    }
);

// 1.初始化react-navigation与redux的中间件
export const middleware = createReactNavigationReduxMiddleware(
    'root',
    state => state.nav
);

// 2.将根导航器组件传递给 reduxifyNavigator 函数(此方法在react-navigation-redux-helpers 3.0版本中有所差异)
const AppNavigationState = reduxifyNavigator(RootNavigator, 'root');
const mapStateToProps = state => ({
    state: state.nav
});

// 3.连接 React 组件与 Redux store
export default connect(mapStateToProps)(AppNavigationState);
  1. store的配置文件;
import {applyMiddleware, createStore} from 'redux'
import reducers from './reducers'
import {middleware} from '../navigator'
const middlewares = [
    middleware    //路由配置文件中创建的中间件
];
export default createStore(reducers, applyMiddleware(...middlewares));
  1. reducer的配置;
import {combineReducers} from 'redux'
import {rootNav, RootNavigator} from '../../navigator';

/* 1.指定默认state */
const navState = RootNavigator.router.getStateForAction(RootNavigator.router.getActionForPathAndParams(rootNav));
/* 2.创建自己的 navigation reducer */
const navReducer = (state = navState, action) => {
    const nextState = RootNavigator.router.getStateForAction(action, state);
    return nextState || state;
};

/* 3. 合并reducer*/
export default combineReducers({
    nav: navReducer  // 和路由配置中的state对应
});
  1. 创建App.js并在index.js中使用;
    App.js:
import React, {Component} from 'react';
import {Provider} from 'react-redux';
import AppNavigator from './navigator';
import store from './store'

type Props = {};
export default class App extends Component {
    render() {
        return 
            
        
    }
}

index.js:

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

你可能感兴趣的:(react-redux和react-natigation的整合。)