前提・実現したいこと
reactでログインしているときとしていないときの画面遷移を行いたい。
stateで管理しているログイン情報を見た際にログインしていれば、ログイン画面に飛ばし
していなければ、URLを変更し画面遷移を行う
例:
ログインしている場合、
/に飛ぼうとした場合、/dashboardにURLを変更しdashboardのcomponentを表示したい
ログインしていない場合
/dashboardに飛ぼうとした場合、/にURLを変更しHomeのcomponentを表示したい
発生している問題・エラーメッセージ
発生問題①
Redirectを一番上にした場合、画面表示自体が行われない
React
1export default function App() { 2 const initialInfo = useSelector(state => state.initial) 3 const classes = useStyles(); 4 return ( 5 <React.Fragment> 6 { 7 initialInfo.isConnect ? 8 <CircularProgress className={classes.progress} /> 9 : 10 <ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */} 11 <Switch> 12 { 13 initialInfo.isLogin ? 14 <Route path="/" render={() => <Redirect to="/dashboard" />} /> 15 : 16 <Route path="/" component={Home}/> 17 } 18 { 19 initialInfo.isLogin ? 20 <Route path="/dashboard" component={Admin}/> 21 : 22 <Route path="/dashboard" render={() => <Redirect to="/" />} /> 23 } 24 {/*<Redirect from="/dashboard" to="/admin/dashboard"/>*/} 25 <Route exact path="/" component={Home}/> 26 <Route exact path="/dashboard" component={Admin}/> 27 <Route component={NoMatch}/> 28 </Switch> 29 </ConnectedRouter> 30 } 31 </React.Fragment> 32 ); 33}
発生問題②
<Route>componentを上に持ってきた場合、Redirectが効かない
React
1export default function App() { 2 const initialInfo = useSelector(state => state.initial) 3 const classes = useStyles(); 4 return ( 5 <React.Fragment> 6 { 7 initialInfo.isConnect ? 8 <CircularProgress className={classes.progress} /> 9 : 10 <ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */} 11 <Switch> 12 <Route exact path="/" component={Home}/> 13 <Route exact path="/dashboard" component={Admin}/> 14 { 15 initialInfo.isLogin ? 16 <Route path="/" render={() => <Redirect to="/dashboard" />} /> 17 : 18 <Route path="/" component={Home}/> 19 } 20 { 21 initialInfo.isLogin ? 22 <Route path="/dashboard" component={Admin}/> 23 : 24 <Route path="/dashboard" render={() => <Redirect to="/" />} /> 25 } 26 {/*<Redirect from="/dashboard" to="/admin/dashboard"/>*/} 27 <Route component={NoMatch}/> 28 </Switch> 29 </ConnectedRouter> 30 } 31 </React.Fragment> 32 ); 33}
補足情報(FW/ツールのバージョンなど)
packagejson
1"react": "^16.10.1", 2 "react-dom": "^16.10.1", 3 "react-ga": "^2.6.0", 4 "react-markdown-loader": "^1.2.1", 5 "react-redux": "^7.1.1", 6 "react-router-dom": "^5.1.2", 7 "redux": "^4.0.4", 8 "redux-logger": "^3.0.6", 9 "redux-saga": "^1.1.1",
あなたの回答
tips
プレビュー