routersModel.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. const router = {
  2. type: 'tab',
  3. getInitialState({ routeNames, routeParamList }) {
  4. const index =
  5. options.initialRouteName === undefined
  6. ? 0
  7. : routeNames.indexOf(options.initialRouteName);
  8. return {
  9. stale: false,
  10. type: 'tab',
  11. key: shortid(),
  12. index,
  13. routeNames,
  14. routes: routeNames.map(name => ({
  15. name,
  16. key: name,
  17. params: routeParamList[name],
  18. })),
  19. };
  20. },
  21. getRehydratedState(partialState, { routeNames, routeParamList }) {
  22. const state = partialState;
  23. if (state.stale === false) {
  24. return state as NavigationState;
  25. }
  26. const routes = state.routes
  27. .filter(route => routeNames.includes(route.name))
  28. .map(
  29. route =>
  30. ({
  31. ...route,
  32. key: route.key || `${route.name}-${shortid()}`,
  33. params:
  34. routeParamList[route.name] !== undefined
  35. ? {
  36. ...routeParamList[route.name],
  37. ...route.params,
  38. }
  39. : route.params,
  40. } as Route<string>)
  41. );
  42. return {
  43. stale: false,
  44. type: 'tab',
  45. key: shortid(),
  46. index:
  47. typeof state.index === 'number' && state.index < routes.length
  48. ? state.index
  49. : 0,
  50. routeNames,
  51. routes,
  52. };
  53. },
  54. getStateForRouteNamesChange(state, { routeNames }) {
  55. const routes = state.routes.filter(route =>
  56. routeNames.includes(route.name)
  57. );
  58. return {
  59. ...state,
  60. routeNames,
  61. routes,
  62. index: Math.min(state.index, routes.length - 1),
  63. };
  64. },
  65. getStateForRouteFocus(state, key) {
  66. const index = state.routes.findIndex(r => r.key === key);
  67. if (index === -1 || index === state.index) {
  68. return state;
  69. }
  70. return { ...state, index };
  71. },
  72. getStateForAction(state, action) {
  73. switch (action.type) {
  74. case 'NAVIGATE': {
  75. const index = state.routes.findIndex(
  76. route => route.name === action.payload.name
  77. );
  78. if (index === -1) {
  79. return null;
  80. }
  81. return { ...state, index };
  82. }
  83. default:
  84. return BaseRouter.getStateForAction(state, action);
  85. }
  86. },
  87. shouldActionChangeFocus() {
  88. return false;
  89. },
  90. };
  91. const SimpleRouter = () => router;
  92. export default SimpleRouter;