over 3 years ago

pageRoutes.js

// 此範例是檢查 localStorage.token 來決定要不要導入登入頁面
// 如條件成立則利用 replace 導入所要的路徑

function  enterRedirectToLogin(nextState, replace) {
  if (!localStorage.token) {
    replace({
      pathname: '/Login',
      state: { nextPathname: nextState.location.pathname }
    });
  }
}

function changeRedirectToLogin(prevState, nextState, replace) {
  if (!localStorage.token) {
    replace({
      pathname: '/Login',
      state: { nextPathname: nextState.location.pathname }
    });
  }
}

function redirectToMain(nextState, replace) {
  if (localStorage.token) {
    replace({
      pathname: '/',
      state: { nextPathname: nextState.location.pathname }
    });
  }
}

export default {
  childRoutes: [
  {
    // 使用 onEnter 直接導入底下 childRoutes path 時觸發 enterRedirectToLogin
    onEnter: enterRedirectToLogin, 
    // 使用 onChange 當 routes location 變動導入底下 childRoutes path 時觸發 changeRedirectToLogin
    onChange: changeRedirectToLogin,
    childRoutes: [
      {
        path: '/',
        getComponent(location, cb) {
          require.ensure([], (require) => {
            cb(null, require('./Home/components/main').default)
          }, 'Home');
        }
      },
      {
        path: '/UserManage',
        getComponent(location, cb) {
          require.ensure([], (require) => {
            cb(null, require('./UserManage/components/main').default)
          },'UserManage');
        }
      }
    ]
  },
  {
    // 使用 onEnter 直接導入底下 childRoutes path 時觸發 redirectToMain
    onEnter: redirectToMain,
    childRoutes: [
      {
        path: '/Login',
        getComponent(location, cb) {
          require.ensure([], (require) => {
            cb(null, require('./Login/components/main').default)
          }, 'Login');
        }
      }
    ]
  }
  ]
};

主頁 index.js

...
..
.
import PageRoutes from './pageRoutes';
...
..
.
render(
  <Provider store={store}>
    <Router history={history} routes={PageRoutes} />
  </Provider>,
  reactElement
);

參考連結
https://github.com/reactjs/react-router/blob/master/docs/API.md#onenternextstate-replace-callback
https://github.com/reactjs/react-router/blob/master/docs/API.md#onchangeprevstate-nextstate-replace-callback

← 使用 webpack code splitting 整合 react-router 和 React 使用 react-i18next 建立多語系 →
 
comments powered by Disqus