React native 实战 -- 导航Navigation Redux(mac)

下载安装

  • 安装导航 react-navigation
  • 安装 react-redux
  • 安装 中间件 redux-logger redux-thunk

导航简单示例

  • app.router.js 文件
import IndexScreen  from  'xxx'  //随便写一个页面
import { StackNavigator } from 'react-navigation';

export const AppNavigator = StackNavigator({
    Index: { screen: IndexScreen },
},
    {
        navigationOptions: {  // 屏幕导航的默认选项, 也可以在组件内用 static navigationOptions 设置(会覆盖此处的设置)
            // 导航栏相关设置项
            headerBackTitle: null,  // 左上角返回键文字
        },
        cardStack: {
            gesturesEnabled: true
        },
        mode: 'card',  // 页面切换模式, 左右是card(相当于iOS中的push效果), 上下是modal(相当于iOS中的modal效果)
        headerMode: 'screen',
    }
);
  • app.reducer.js 文件
import { AppNavigator } from './app.router';
const initialState = AppNavigator.router.getStateForAction(AppNavigator.router.getActionForPathAndParams('Index'));

export default navReducer = (state = initialState, action) => {
    const nextState = AppNavigator.router.getStateForAction(action, state);
    return nextState || state;
};
  • app.js 文件
import React, { Component } from 'react';
import { addNavigationHelpers } from 'react-navigation';
import { AppNavigator } from './app.router';
import { connect } from 'react-redux';
class App extends Component {
    render() {
        return(
        
        );
    }
}
mapStateToProps = (store) => ({
    nav: store.navReducer,
});
export const AppState = connect(mapStateToProps)(App);
  • router.redux.js
import thunkMiddleware from 'redux-thunk';  // 异步
import { createLogger } from 'redux-logger';  // log
import { createStore, applyMiddleware,combineReducers } from 'redux';

import navReducer from './app/app.reducer'; //导航

let middleware = [thunkMiddleware];
if(__DEV__){
    let loggerMiddleware = createLogger();
    middleware=[...middleware,loggerMiddleware];
}else {
    middleware=[...middleware];
}
const todoStore = combineReducers({
    navReducer,
});
export const store = createStore(
    todoStore,
    applyMiddleware(...middleware)
);
  • index.js 文件
import { AppRegistry } from 'react-native';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { AppState } from './app/app';
import { store } from './Redux/router.redux';
class Router extends Component {
 render() {
        return (
            
                
            
        );
    }
}

AppRegistry.registerComponent('RNTEST', () => Router);

正式使用

  • 遇到的问题,导航无法解析tab,stack嵌套,或者draw嵌套
  • android使用导航redux之后,只要应用没从后台结束,导航state会保持上一次的状态

你可能感兴趣的:(React native 实战 -- 导航Navigation Redux(mac))