公众号

React即将入门了

- - 阅 506

其实1年前就想入门React,后来一是React还是有些门槛的,二则现在这两个项目后端虽然使用了Spring Cloud,前后端做了分离,但还没有使用React、Vue这样的前端做彻底的前后端分离,心中一直很痒,最近这两周不是太忙,就下决心入手React。

经过1周反复入门和演练,从Github上下载了精简版的React+Route+Antd+Fetch,今天终于入门了,做了一个简单的登陆。

Spring boot 那里就不多说了,用户名、密码验证后,使用JWT生成access_token,返回给前台,然后前台每次调用API,就带着这个access_token

Fetch跟后台交互代码如下:

import React, { Component } from ‘react’;
import ‘../../assets/login.less’;
import { Form, Icon, Input, Button, Checkbox, message, Spin } from ‘antd’;

const FormItem = Form.Item;

class NormalLoginForm extends Component {
state = {
isLoding:false,
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log(‘Received values of form: ‘, values);
let that = this;
let username=values.username;
let password=values.password;
let userpassword=”username=”+username+”&password=”+password;
fetch(‘http://127.0.0.1:8800/luban/login’, {
method: ‘POST’,
mode: ‘cors’,
credentials: ‘include’,
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’
},
body:userpassword
}).then(function(response){
if(response.ok) {
response.json().then(function(obj) {
// 这样数据就转换成json格式的了
let code=obj.code;
let access_token=obj.access_token;
if(code==200){
localStorage.setItem(‘luban_user’,JSON.stringify(values));
message.success(‘login successed!’); //成功信息
setTimeout(function() { //延迟进入
that.props.history.push({pathname:’/app’,state:values});
}, 1000);
}else{
message.error(‘用户名或密码不正确!’); //失败信息
}
})
}
}).catch(function (error) {
console.log(‘Request failed’, error);
});

}
});
};

render() {
const { getFieldDecorator } = this.props.form;
return (
this.state.isLoding?<Spin size=”large” className=”loading” />:
<div className=”login”>
<div className=”login-form”>
<div className=”login-logo”>
<div className=”login-name”>鲁班表单大师</div>
</div>
<Form onSubmit={this.handleSubmit} style={{maxWidth: ‘300px’}}>
<FormItem>
{getFieldDecorator(‘username’, {
rules: [{ required: true, message: ‘请输入用户名!’ }],
})(
<Input prefix={<Icon type=”user” style={{ fontSize: 13 }} />} placeholder=”用户名” />
)}
</FormItem>
<FormItem>
{getFieldDecorator(‘password’, {
rules: [{ required: true, message: ‘请输入密码!’ }],
})(
<Input prefix={<Icon type=”lock” style={{ fontSize: 13 }} />} type=”password” placeholder=”密码” />
)}
</FormItem>
<FormItem style={{marginBottom:’0′}}>
{getFieldDecorator(‘remember’, {
valuePropName: ‘checked’,
initialValue: true,
})(
<Checkbox>记住我</Checkbox>
)}
<a className=”login-form-forgot” href=”” style={{float:’right’}}>忘记密码?</a>
<Button type=”primary” htmlType=”submit” className=”login-form-button” style={{width: ‘100%’}}>
登录
</Button>
或者 <a href=””>现在就去注册!</a>
</FormItem>
</Form>
</div>
</div>
);
}
}

const Login = Form.create()(NormalLoginForm);
export default Login;

0

本文转载 " "

原文地址 " "

相关文章!