react-navigation集成Redux

之前觉得将react-navigation集成redux完全没什么必要,因为react-navigation基本可以满足日常导航的开发和使用,可是当项目需求足够复杂的时候,你会发现react-navigation集成redux是一件多棒的事情。
在react-navigation goBack()传参返回无效文章中遇到的问题用下面讲的这个方法可以完美解决:react-navigation集成Redux之后,能获取当前screen的key,routeNmae等参数,goBack()的时候就可以直接取到key,不需要修改源码。
一、集成 我们还用上篇的项目集成。
1.添加addNavigationHelpers 找到app.js,代码如下:

... import { addNavigationHelpers, NavigationActions, } from 'react-navigation'; import AppNavigator from '../constants/routers'; ... render() { const { dispatch, nav } = this.props; return ( { this.navigator = nav; }} navigation={addNavigationHelpers({ dispatch: dispatch, state: nav })} /> ); } const mapStateToProps = state =>({ nav: state.nav, }); export default connect(mapStateToProps)(App);

2. 创建navReducer 在reducers文件夹下新建navReducer.js
/** * Created by sybil052 on 2017/9/28. */ import Routers from '../constants/routers'; const recentlyVisitedRoutes = new Set(); //防止連點,多次navigate,增加此判斷 const navReducers = (state, action) => { if (action.type === 'Navigation/NAVIGATE') { if (recentlyVisitedRoutes.has(action.routeName)) { return state; } recentlyVisitedRoutes.add(action.routeName); setTimeout(() => { recentlyVisitedRoutes.delete(action.routeName); }, 400); } const newState = Routers.router.getStateForAction(action, state); return newState || state; }; export default navReducers;

3.修改index 依旧在reducers文件夹下找到index.js,添加navReducers
... import nav from './navReducers'; const rootReducer = combineReducers({ app, ... nav, }); export default rootReducer;

二、使用 1. 在mapStateToProps中添加routes
function mapStateToProps(state) { return { routes: state.nav.routes, ... }; }

2.获取routes
// 返回上上个界面 back() { const routes = this.props.routes; console.log(routes); let key = routes[routes.length-2].key; this.props.navigation.goBack(key); }

【react-navigation集成Redux】好了,react-navigation集成redux已经完结,我们只需要在想获取routes的界面mapStateToProps中添加routes: state.nav.routes,就能获取到项目跳转的全部路由啦~

    推荐阅读