React redux starter kit でのルーティングで認証画面を挟んで、ログインページと、コンテンツページを分けるときに参考になったページをメモ
- childRoutes 配列内にコンポーネントのパスを入れて、
onEnter
パラメータに認証に失敗したときのパスなどの条件分岐をすればよいらしい。
function requireAuth (nextState, replace, callback) {
const token = localStorage.getItem('@TOKEN')
if (!token) replace('/')
return callback()
}
// ...
export const createRoutes = (store) => ({
path: '/',
childRoutes: [
// Authenticated
{
component: CoreLayout,
onEnter: requireAuth, // add this
indexRoute: Dashboard,
childRoutes: [
ProfileRoute(store),
BillingRoute
]
},
// Not-authenticated
{
component: ModalLayout,
childRoutes: [
LoginRoute
]
},
// Other Not-authenticated routes
HelpRoute,
ContactRoute
]
})
参考ページ
https://medium.com/@peterpme/react-router-authentication-onenter-requireauth-plainroute-a-follow-up-to-a-github-issue-71ea3e7d59c9