import React from 'react';
import {createStackNavigator, createSwitchNavigator} from 'react-navigation';
import {connect} from 'react-redux';
import {createReactNavigationReduxMiddleware, reduxifyNavigator} from 'react-navigation-redux-helpers';
export const rootCom = 'Init';//設置根路由
export const RootNavigator = createSwitchNavigator({
...
});
/** * 1.初始化react-navigation與redux的中間件, * 該方法的一個很大的做用就是爲reduxifyNavigator的key設置actionSubscribers(行爲訂閱者) * 設置訂閱者@https://github.com/react-navigation/react-navigation-redux-helpers/blob/master/src/middleware.js#L29 * 檢測訂閱者是否存在@https://github.com/react-navigation/react-navigation-redux-helpers/blob/master/src/middleware.js#L97 * @type {Middleware} */
export const middleware = createReactNavigationReduxMiddleware(
state => state.nav,
'root'
);
/** * 2.將根導航器組件傳遞給 reduxifyNavigator 函數, * 並返回一個將navigation state 和 dispatch 函數做爲 props的新組件; * 注意:要在createReactNavigationReduxMiddleware以後執行 */
const AppWithNavigationState = reduxifyNavigator(RootNavigator, 'root');
/** * State到Props的映射關係 * @param state */
const mapStateToProps = state => ({
state: state.nav,//v2
});
/** * 3.鏈接 React 組件與 Redux store */
export default connect(mapStateToProps)(AppWithNavigationState);
複製代碼
注意
createReactNavigationReduxMiddleware
方法,react-navigation-redux-helpers3.0
後參數順序發生了變化。2019-04-29 使用了react-navigation-redux-helpers3.0的請注意。不然會報錯redux root is not a function (evaluating 'navStateSelector(newState)')
git
import {combineReducers} from 'redux'
import {rootCom, RootNavigator} from '../../navigators/AppNavigators';
//1.指定默認state
const navState = RootNavigator.router.getStateForAction(RootNavigator.router.getActionForPathAndParams(rootCom));
/** * 2.建立本身的 navigation reducer, */
const navReducer = (state = navState, action) => {
const nextState = RootNavigator.router.getStateForAction(action, state);
// 若是`nextState`爲null或未定義,只需返回原始`state`
return nextState || state;
};
/** * 3.合併reducer * @type {Reducer<any> | Reducer<any, AnyAction>} */
const index = combineReducers({
nav: navReducer,
});
export default index;
複製代碼
import {applyMiddleware, createStore} from 'redux'
import reducers from '../redux/index'
import {middleware} from '../../navigators/AppNavigators';
const middlewares = [
middleware,
];
/** * 建立store */
export default createStore(reducers, applyMiddleware(...middlewares));
複製代碼
import AppNavigator from './navigators/AppNavigators'
import React, {Component} from 'react';
import store from './pages/store/index'
import {Provider} from 'react-redux';
type Props = {};
export default class App extends Component<Props> {
render() {
/** * 將store傳遞給App框架 */
return <Provider store={store}> <AppNavigator/> </Provider> }
}
複製代碼
配置成功,各步驟對應文件 以下: github