路由守卫
- 新建路由页面RouterPage.js
import React, { Component } from 'react'; import {BrowserRouter, Link, Route, Switch} from 'react-router-dom'; import HomePage from './HomePage'; import UserPage from './UserPage'; import LoginPage from './LoginPage'; import SearchPage from './SearchPage'; import PrivateRoutePage from './PrivateRoutePage'; export default class RouterPage extends Component { render() { const id = Math.random(); return ( <div> <h1>RouterPage</h1> <BrowserRouter> <Link to="/">首页</Link> <Link to="/user">用户中心 </Link> {/* <Link to="/login">LoginPage </Link> */} <Link to={`/search/${id}`}>搜索页面 </Link> <Link to="/a">404 </Link> <Switch> {/* 渲染优先级:children > component > render */} {/* <Route exact component={HomePage} path="/" /> */} {/* 路由守卫 */} <PrivateRoutePage exact component={HomePage} path="/" /> <PrivateRoutePage component={UserPage} path="/user" /> <Route component={LoginPage} path="/login" /> <PrivateRoutePage component={SearchPage} path="/search/:id" /> <Route component={() => (<h1>404</h1>)} /> </Switch> </BrowserRouter> </div> ) } }
- 路由守卫页面逻辑
- 登录信息存储在store中
- 没有登录时,重定向页面,并且存储当前页面path, 在state中
-
import React, { Component } from 'react' import {Route, Redirect} from 'react-router-dom' import {connect} from 'react-redux'; @connect( state => state.user, ) class PrivateRoutePage extends Component { render() { const {path, component, isLogin} = this.props; console.log('&&&&&&&&&&', this.props); if(isLogin) { return <Route component={component} /> } else { return ( <Redirect to={{ pathname: '/login', state: {redirect: path} }} /> ) } } } export default PrivateRoutePage
- 登录页面逻辑
- 没有登录,显示登录页面信息
- 登录了,页面重定向之前的页面
-
import React, { Component } from 'react' import {Button} from 'antd' import {connect} from 'react-redux' import { Redirect } from 'react-router-dom'; @connect( // mapStateToProps state => state.user, // mapDispatchToProps { login: () => ({type: "loginSuccess"}) } ) class LoginPage extends Component { // 登录 handleLogin = () => { this.props.login(); } render() { const {location, isLogin} = this.props; console.log('props====', this.props); const {redirect = '/'} = location.state; if (isLogin) { return (<Redirect to={redirect} />) } else { return ( <div> <h1>LoginPage</h1> { !isLogin && ( <Button type="primary" onClick={this.handleLogin}>登录</Button> ) } </div> ) } } } export default LoginPage
你对生活笑,生活不会对你哭。