react-navigation集成redux的小demo

react-navigation是導航,用于場景(頁面)的跳轉(zhuǎn)。redux是狀態(tài)管理器,它同樣使用于移動端,我們可以用redux來管理app的場景變換。熟悉wb前端的伙伴都知道,redux有三要素,store、reducer、action,用來管理項目的state,使得數(shù)據(jù)變化可以追蹤。

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: 根據(jù)給定的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(發(fā)一個action請求),進入reducer,根據(jù)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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容