使用react-router4.0实现重定向和404功能的方法
在开发中,重定向和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页面
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
- 详解React中传入组件的props改变时更新组件的几种实现方法
- VSCode配置react开发环境的步骤
- react-redux中connect的装饰器用法@connect详解
- ReactNative 之FlatList使用及踩坑封装总结
- React Native实现简单的登录功能(推荐)
- ReactNative之键盘Keyboard的弹出与消失示例
- react-router browserHistory刷新页面404问题解决方法
- 详解React Native开源时间日期选择器组件(react-native-datetime)
- react中使用swiper的具体方法
- React useMemo和useCallback的使用场景
相关文章
在react中使用highlight.js将页面上的代码高亮的方法
本文通过 highlight.js 库实现对文章正文 HTML 中的代码元素自动添加语法高亮,具有一定的参考价值,感兴趣的可以了解一下2022-01-01
React-View-UI组件库封装Loading加载中源码
这篇文章主要介绍了React-View-UI组件库封装Loading加载样式,主要包括组件介绍,组件源码及组件测试源码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-06-06


最新评论