使用react-router4.0实现重定向和404功能的方法
在开发中,重定向和404这种需求非常常见,使用React-router4.0可以使用Redirect进行重定向
最常用的就是用户登录之后自动跳转主页。
importReact,{Component}from'react';
importaxiosfrom'axios';
import{Redirect}from'react-router-dom';
classLoginextendsComponent{
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(
)
}
return(
{this.toLogin(this.state.value)}}>登录
)
}
}
exportdefaultLogin;
以上这个示例仅仅是将登录的状态作为组件的state使用和维护的,在实际开发中,是否登录的状态应该是全局使用的,因此这时候可能你会需要考虑使用redux等这些数据状态管理库,方便我们做数据的管理。这里需要注意的使用传统的登录方式使用cookie存储无序且复杂的sessionID之类的来储存用户的信息,使用token的话,返回的可能是用户信息,此时可以考虑使用sessionStorage、localStorage来储存用户信息(包括头像、用户名等),此时书写reducer时需要指定初始状态从存储中获取,如:
constLOGIN_SUCCESS='LOGIN_SUCCESS';
constLOGIN_FAILED='LOGIN_FAILED';
constLOGINOUT='LOGINOUT';
constLogin=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){
caseLOGIN_SUCCESS:
return{logined:true,usermsg:action.usermsg};
caseLOGIN_FAILED:
return{logined:false,usermsg:{}};
caseLOGINOUT:
return{logined:false,usermsg:{}};
default:
returnstate
}
};
exportdefaultLogin;
指定404页面也非常简单,只需要在路由系统最后使用Route指定404页面的component即可
当路由指定的所有路径没有匹配时,就会加载这个NoMatch组件,也就是404页面
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。