本地存储 – localStorage
- 登录请求成功后,将返回的result存入localStorage
//action/login.js
import Ajax from '../utils/ajax';
import Storage from '../utils/storage';
import {message} from 'antd';
const sto = new Storage();
{/* 用户登录 */}
export function userLogin(postData){
return (dispatch, getState)=>{
Ajax.post({
url: 'http://127.0.0.1:3000/user/login',
data: postData,
error(){
window.location.href="#/home";
},
success(res){
const result = res.body;
if(result.code === "200"){
dispatch({
type: 'USER_LOGIN',
username: result.userName,
userId: result.userId,
userState: result.userState,
message: result.msg
});
message.success("登录成功,欢迎您!");
window.location.href="#/home";
sto.setStorage('userInfo',result);
}else{
dispatch({
type: 'GET_ERRORS',
error: result.msg
});
message.error("登录失败,请重试!");
}
}
})
}
}
//utils/storage.js
class Storage{
// 本地存储
setStorage(name, data){
let dataType = typeof data;
// json对象
if(dataType === 'object'){
window.localStorage.setItem(name, JSON.stringify(data));
}
// 基础类型
else if(['number','string','boolean'].indexOf(dataType) >= 0){
window.localStorage.setItem(name, data);
}
// 其他不支持的类型
else{
alert('该类型不能用于本地存储');
}
}
// 取出本地存储内容
getStorage(name){
let data = window.localStorage.getItem(name);
if(data){
return JSON.parse(data);
}
else{
return '';
}
}
// 删除本地存储
removeStorage(name){
window.localStorage.removeItem(name);
}
}
export default Storage;
如下图:
- 在页面中将localStorage中的username取出,渲染在用户界面中
state = {
username: sto.getStorage('userInfo').userName
}
<Menu.Item key="2">
<Avatar src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550649854081&di=f3293e7699c3ab413df652f3600bad85&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201707%2F19%2F20170719124043_tdvL2.jpeg" style={{ backgroundColor: '#fff' }} />
{
this.state.username
? <span className="welcome">欢迎登录,{this.state.username}</span>
: <span className="welcome">欢迎您</span>
}
</Menu.Item>
效果图如下:
- 点击退出时,清除localStorage记录
//home/index.jsx
import { Layout, Menu, Breadcrumb, Icon } from 'antd';
import React, { Component, PropTypes } from 'react';
import { Avatar } from 'antd';
import Storage from '../../utils/storage';
const sto = new Storage();
<Menu.Item key="1" onClick={() => {
sto.removeStorage('userInfo');
this.props.router.push('/login');
}}><Icon type="logout" />退出
</Menu.Item>