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

时间:2021-05-25

在开发中,重定向和404这种需求非常常见,使用React-router4.0可以使用Redirect进行重定向

最常用的就是用户登录之后自动跳转主页。

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时需要指定初始状态从存储中获取,如:

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即可

<Switch> <Route path="/" exact component={Home}/> <Route path="/user" component={User}/> <Route component={NoMatch}/></Switch>

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章