当用户没有登录的时候, 有些页面不能允许其访问.
具体的做法是: 重新自定义一个路由, 然后依据用户时候登录, 执行跳转逻辑


比如, 用户未登录, Topic 页面就不允许他访问, 转而跳转至登录界面, 这类似与Vue的导航守卫. 但是react没有提供这类API
PrivateRoute.js

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
// 这个组件将根据登录的情况, 返回一个路由
const PrivateRoute = ({component: Component, ...props}) => {
    // 解构赋值 将 props 里面的 component 赋值给 Component
    return <Route {...props} render={(p) => {
        const login = document.cookie.includes('login=true')
        if (login){ // 如果登录了, 返回正确的路由
            return <Component />
        } else { // 没有登录就重定向至登录页面
            alert("你还没有登录哦, 确认将跳转登录界面进行登录!")
            return <Redirect to={{
                pathname: '/login',
                state: {
                    from: p.location.pathname
                }
            }}/>
        }
    }}/>
}
export default PrivateRoute

Login.js

import React from 'react'
import './login.css'

export default class Login extends React.Component{
    state = {
        isLogin: document.cookie.includes('login=true')
    }
    handleClick = () => {
        let login = !this.state.isLogin
        this.setState({
            isLogin: login
        })
        if(login){
            // 设置cookie之后跳转回来时的页面
            this.setCookie('login', true, 15)
            this.jumpBack()
        } else {
            // 设置时间为负数, 取消设置的 cookie
            this.setCookie('login', '', -1)
        }

    }
    setCookie = (key, value, day) => {
        let expires = day * 86400 * 1000  // 时间转化成 ms
        let date = new Date( + new Date() + expires) // 当前时间加上要存储的时间
        document.cookie = `${key}=${value};expires=${date.toUTCString()}`
    }
    jumpBack = () => {
        // 打哪儿来回哪去
        const { location } = this.props
        const from = location.state && location.state.from
       //  const article = location.state && location.state.article
        this.props.history.push({
            pathname: from,
            state: {
                // article
            }
        })
    }
    render() {
        return (
            <div className={'login'}>
                <button className={'login-btn'} onClick={this.handleClick}>{ this.state.isLogin ? '退出' : '登录' }</button>
            </div>
        );
    }
}

通过设置浏览器cookie 模拟了用户登录或者未登录.
当匹配到这个路由的时候, 首先就会去判断这个用户是否登录了, 如果是,就返回应该给用户看到的组件Component, 如果不是, 就提醒用户去登录, 并且跳转到登录页面.RedirectLogin页面.
如果用户在登录了之后, 希望直接跳转回Topic页面, 而不用手动, 那么就将当前路径pathname传递过去, 在Login页面确认用户登录之后, 再根据这个传递过去的pathname直接Redirect回到Topic页面.