react-router4.0 访问其他页面未登录时跳到登录页

没有登录直接访问页面跳转到登录页,官网的例子很详细了,参照官网做以下调整:
先把Route封装一下,判断一下用户是否登录,如果登录则正常router跳转,如果未登录则跳转登录页。代码:
privateRoute.jsx

import React, {Component} from 'react';
import {Route, withRouter} from 'react-router-dom';

class PrivateRoute extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: window.sessionStorage.getItem("userId") ? true: false
        }
    }

    componentWillMount() {
        if(!this.state.isAuthenticated){
            const {history} = this.props;
            setTimeout(() => {
                history.replace("/login");
            }, 1000)
        }
    }

    render() {
        let { component: Component, ...rest} = this.props;
        return  this.state.isAuthenticated ? 
        (<Route {...rest} render={(props) => ( <Component {...props} /> 
            )}/> ) : (<p style = {{"width": "100%", "text-align": "center", "fontSize": "20px", "lineHeight": "50px"}}>请登录...</p>)

    }
}

export default withRouter(PrivateRoute);

刚刚封装的路由引入页面

import PrivateRoute from "./privateRoute";

这里写图片描述

这样就可以了

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React Router DOM是一个用于React应用程序的路由库,它可以帮助我们实现页面之间的导航和路由控制。在默认情况下,当我们在React应用程序中使用React Router DOM进行页面跳转页面不会进行刷新,而是通过JavaScript来动态地切换组件。 然而,如果你希望在页面跳转进行页面刷新,可以使用以下方法之一: 1. 使用window.location.reload()方法:在路由跳转,使用window.location.reload()方法强制浏览器进行页面刷新。可以在需要刷新的地方调用该方法,例如路由的onClick事件处理程序中。 ```jsx import { useHistory } from 'react-router-dom'; const MyComponent = () => { const history = useHistory(); const handleRouteClick = () => { // 执行路由跳转后刷新页面 history.push('/new-route'); window.location.reload(); }; return ( <button onClick={handleRouteClick}>Go to new route</button> ); }; ``` 2. 使用forceRefresh选项:在使用BrowserRouter作为根路由器,可以通过将forceRefresh选项设置为true来实现页面刷新。这将强制浏览器在路由切换进行完整的页面刷新。 ```jsx import { BrowserRouter as Router, Route } from 'react-router-dom'; const App = () => { return ( <Router forceRefresh={true}> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Router> ); }; ``` 需要注意的是,在大多数情况下,使用React Router DOM的默认行为来动态更新组件而不进行页面刷新通常是更好的选择。只有在特定的需求下才需要强制页面刷新。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值