前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用react-router4.0实现重定向和404功能

使用react-router4.0实现重定向和404功能

作者头像
用户1515472
发布2019-07-24 14:28:48
1.1K0
发布2019-07-24 14:28:48
举报

在使用react开发中,重定向和404这种需求非常常见,使用React-router4.0可以使用Redirect进行重定向 最常用的就是用户登录之后自动跳转主页。

代码语言:javascript
复制
import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

class Login extends Component{
  constructor(){
    super();
    this.state = {value: '', logined: false};
    this.handleChange = this.handleChange.bind(this);
    this.toLogin = this.toLogin.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value})
  }

  toLogin(accesstoken) {
    axios.post('yoururl',{accesstoken})
      .then((res) => {
        this.setState({logined: true});
      })
  }

  render() {
    if(this.props.logined) {
      return (
        <Redirect to="/user"/>
      )
    }
    return (
      <div>
          <input type="text" value={this.state.value} onChange={this.handleChange} />
          <a onClick={() => { this.toLogin(this.state.value) }}>登录</a>
      </div>
    )
  }
}

export default Login;

以上这个示例仅仅是将登录的状态作为组件的state使用和维护的,在实际开发中,是否登录的状态应该是全局使用的,因此这时候可能你会需要考虑使用redux等这些数据状态管理库,方便我们做数据的管理。这里需要注意的使用传统的登录方式使用cookie存储无序且复杂的sessionID之类的来储存用户的信息,使用token的话,返回的可能是用户信息,此时可以考虑使用sessionStorage、localStorage来储存用户信息(包括头像、用户名等),此时书写reducer时需要指定初始状态从存储中获取,如:

代码语言:javascript
复制
const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
const LOGIN_FAILED = 'LOGIN_FAILED';
const LOGINOUT = 'LOGINOUT';

const Login = function(state, action) {
  if(!state) {
    console.log('state');
    if(sessionStorage.getItem('usermsg')) {
      return {
        logined: true,
        usermsg: JSON.parse(sessionStorage.getItem('usermsg'))
      }
    }
    return {
      logined: false,
      usermsg: {}
    }
  }
  switch(action.type) {
    case LOGIN_SUCCESS:
      return {logined: true,usermsg: action.usermsg};
    case LOGIN_FAILED:
      return {logined: false,usermsg:{}};
    case LOGINOUT:
      return {logined: false, usermsg: {}};
    default:
      return state
  }
};

export  default Login;

指定404页面也非常简单,只需要在路由系统最后使用Route指定404页面的component即可

代码语言:javascript
复制
<Switch>
  <Route path="/" exact component={Home}/>
  <Route path="/user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

当路由指定的所有路径没有匹配时,就会加载这个NoMatch组件,也就是404页面

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档