美文网首页ReactNative
react-navigation集成redux的小demo

react-navigation集成redux的小demo

作者: 埃米莉Emily | 来源:发表于2017-07-09 00:45 被阅读2709次

react-navigation是导航,用于场景(页面)的跳转。redux是状态管理器,它同样使用于移动端,我们可以用redux来管理app的场景变换。熟悉wb前端的伙伴都知道,redux有三要素,store、reducer、action,用来管理项目的state,使得数据变化可以追踪。

store

store = createStore(AppReducer);

reducer:AppReducer里列出了项目的所有reducer。

const AppReducer = combineReducers({
  nav,
  auth,
});

初始加载的页面在initialNavState里。

// Start with two routes: The Main screen, with the Login screen on top.
const firstAction = AppNavigator.router.getActionForPathAndParams('Main');
const tempNavState = AppNavigator.router.getStateForAction(firstAction);
const secondAction = AppNavigator.router.getActionForPathAndParams('Login');
const initialNavState = AppNavigator.router.getStateForAction(
  secondAction,
  tempNavState
);

nav和auth都是改变state的function。

function nav(state = initialNavState, action) {
  let nextState;
  switch (action.type) {
    case 'Login':
      nextState = AppNavigator.router.getStateForAction(  //  getStateForAction: 根据给定的action来定义返回的navigation sate
        NavigationActions.back(),   // action  返回上一屏幕并关闭当前屏幕
        state                       // state
      );
      break;
    case 'Logout':
      nextState = AppNavigator.router.getStateForAction(
        NavigationActions.navigate({ routeName: 'Login' }),    // 通过navigat action 改变当前state
        state
      );
      break;
    default:
      nextState = AppNavigator.router.getStateForAction(action, state);
      break;
  }

  // Simply return the original `state` if `nextState` is null or undefined.
  return nextState || state;
}

action:当用户进行操作从而切换场景时,我们可以dispatch一个特定的type(发一个action请求),进入reducer,根据type来进行相应改变。

<Button
  onPress={() => navigation.dispatch({ type: 'Login' })}
  title="Log in"
/>

页面的切换我们将用到NavigationActions的navigate api。

NavigationActions.navigate({ routeName: 'Login' })

因此我们要将所有type对应的screen制定好。

import LoginScreen from '../components/LoginScreen';
import MainScreen from '../components/MainScreen';
import ProfileScreen from '../components/ProfileScreen';
...
export const AppNavigator = StackNavigator({   // 堆栈导航,所有屏幕的集合
  Login: { screen: LoginScreen },
  Main: { screen: MainScreen },
  Profile: { screen: ProfileScreen },
});

StackNavigator和TabNavigator是最常用的导航器,demo里就有简单用到,完整代码请进入react-navigation-SimpleApp

相关文章

网友评论

    本文标题:react-navigation集成redux的小demo

    本文链接:https://www.haomeiwen.com/subject/tyojhxtx.html