完善路由权限控制和登陆逻辑。因为没有后台接口,所以写了个假数据,来获取登陆用户数据
1 修改 Login 组件,加入验证逻辑以及登陆逻辑
import React , {Component}from ‘react’;
import PropTypes from ‘prop-types’;
import {connect} from ‘dva’;
import {Form, Icon, Input, Button, Checkbox} from ‘antd’;
import {message} from ‘antd’;
import {routerRedux} from ‘dva/router’;
const backgroundImage = require(‘../assets/back.jpg’);
const FormItem = Form.Item;
class Login extends Component{
handleSubmit = (e) => {
e.preventDefault();
const {dispatch} = this.props
this.props.form.validateFields((err, values) => {
if (!err) {
const {userName,password} = values
dispatch({type: ‘user/login’, payload: { userName,password} })
}
});
}
render() {
const {getFieldDecorator,getFieldError} = this.props.form
return (
<div style={styles.form}>
<h1> 登陆 </h1>
<Form onSubmit={this.handleSubmit}>
<FormItem>
{getFieldDecorator(‘userName’, {
rules: [{required: true, message: ‘ 请输入用户名 ’},
{max:20,message: ‘ 最大长度不能超过 20’}],
})(
<Input prefix={<Icon type=”user” style={{ color: ‘rgba(0,0,0,.25)’ }} />} placeholder=” 用户名 ” />
)}
</FormItem>
<FormItem>
{getFieldDecorator(‘password’, {
rules: [{required: true, message: ‘ 请输入密码 ’},
{pattern:/^(?![^a-zA-Z]+$)(?!\D+$)/,message: ‘ 密码必须包含数字和字母 ’},
{min:6,message: ‘ 最小长度为 6 位 ’},
{max:12,message: ‘ 最大长度 12 位 ’},],
})(
<Input prefix={<Icon type=”lock” style={{ color: ‘rgba(0,0,0,.25)’ }} />} type=”password” placeholder=” 密码 ” />
)}
</FormItem>
<FormItem>
<Checkbox> 记住我 </Checkbox>
<Button block type=”primary” onClick={this.handleSubmit}>
登陆
</Button>
<a> 忘记密码 </a>
或 <a href=”#/reg”> 注册!</a>
</FormItem>
</Form>
</div>
)
}
componentWillMount () {
if(this.props.state.user.isLogin) {
this.props.dispatch(routerRedux.push(‘/’))
}
}
}
const styles = {
form: {
maxWidth: ‘400px’,
margin: ‘0 auto’,
paddingTop: ‘100px’,
}
};
Login.propTypes = {
};
function mapStateToProps(state) {
return {
state
}
}
// export default ListData;
export default connect(mapStateToProps)(Form.create()(Login));
主要是验证规则的书写,支持很多,可以在 antd 官网查看具体使用,我只是验证了些简单的,不为空,最大最小长度以及正则验证密码。还有就是判断如果已经登陆直接跳转到首页。
2 创建 userService 来获取登陆用户的数据
export function getUser({userName,password}) {
return {
userName: `${userName}`,
password: `${password}`,
job: ‘ 阿里巴巴 java 开发工程师 ’,
like: ‘ 打篮球 ’,
sex: ‘ 男 ’,
phone: ‘1433545345’,
blog: ‘https://blog.csdn.net/elite1991′,
work:’ailibaba’,
location:’ 杭州阿里巴巴软件园 ’,
name:’mike 晓 ’,
desp:’ 老夫写代码,只用 jquery’
};
}
返回的是假数据,如果你有后台接口,可以换成你自己的
3 创建 usermodel 来保存登陆的用户信息
import * as userService from ‘../services/userService’;
import {routerRedux} from ‘dva/router’;
export default {
namespace: ‘user’,
state:{
isLogin:false,
user:{}
},
effects: {
*login({payload: { userName,password} }, {call, put}) {
const result = yield call(userService.getUser, { userName,password})
yield put({
type: ‘updateUser’,
payload: {
result
}
})
yield put(routerRedux.push(‘/’))
},
},
reducers: {
‘updateUser'(state, { payload: data}) {
let r = data.result
return {isLogin:true,user:r}
}
},
};
注意登陆完后使用 routerRedux 跳转到首页。然后别忘了注册 usermodel,这样简单的登陆功能就完成了。
4 创建 AuthRouter 权限路由父组件
使用它来包裹子路由,在父组件进行登陆判断,如果没有登陆就 redirect 到首页
import React, {Component} from ‘react’
import {connect} from ‘dva’;
import {Router, Route, Redirect, withRouter} from ‘dva/router’;
import {message} from ‘antd’;
class AuthRouter extends Component {
render() {
const {component: Component, …rest} = this.props
const isLogged = this.props.state.user.isLogin
if (!isLogged) {
message.warning(‘ 您需要先登陆 ’);
}
return (
<Route {…rest} render={props => {
return isLogged
? <Component {…props} />
: <Redirect to=”/login” />
}} />
)
}
}
function mapStateToProps(state) {
return {
state
}
}
// export default ListData;
export default connect(mapStateToProps)(withRouter(AuthRouter));
5 改造之前的路由,/apipath 进行授权判断
import React from ‘react’;
import {Router, Route, Switch} from ‘dva/router’;
import IndexPage from ‘./routes/IndexPage’;
import DetailPage from ‘./routes/DetailPage’;
import NewUserPage from ‘./routes/NewUserPage’;
import ApiPage from ‘./routes/ApiPage’;
import AboutPage from ‘./routes/AboutPage’;
import LoginPage from ‘./routes/LoginPage’;
import RegPage from ‘./routes/RegPage’;
import AuthRouter from ‘./components/AuthRouter’;
function RouterConfig({history}) {
return (
<Router history={history}>
<Switch>
<Route path=”/” exact component={IndexPage} />
<Route path=”/detail/:id” exact component={DetailPage} />
<Route path=”/into” exact component={NewUserPage} />
<Route path=’/about’ component={AboutPage}/>
<Route path=”/login” exact component={LoginPage} />
<Route path=”/reg” exact component={RegPage} />
<AuthRouter path=’/api’ component={ApiPage}></AuthRouter>
</Switch>
</Router>
);
}
export default RouterConfig;
这样一来,访问 /api 时会跳转到登陆页,登陆完后就可以正常访问 apiPage 了今天的课程就到这里了,别忘了关注我 mike 啥都想搞