honghaitzz11 6 éve
szülő
commit
6a4e9ad032

+ 4 - 1
src/api/user.jsx

@@ -2,13 +2,16 @@
  * @Author: Johnhong9527
  * @Date:   2019-05-26 12:01:45
  * @Last Modified by:   Johnhong9527
- * @Last Modified time: 2019-05-26 14:17:07
+ * @Last Modified time: 2019-05-26 16:01:45
  */
 import { post, get } from 'util/http.jsx';
 export default class User {
   login(loginInfo) {
     return post('/manage/user/login.do', loginInfo);
   }
+  logout() {
+    return post('/user/logout.do');
+  }
   // 检查登陆接口的数据是不是合法
   checkLoginInfo(loginInfo) {
     let username = `${loginInfo.username}`,

+ 15 - 31
src/component/side-nav/index.jsx

@@ -1,18 +1,11 @@
 import React from 'react';
 import { Menu, Icon, Button, Switch } from 'antd';
 import { BrowserRouter as Router, Route, Link, withRouter } from 'react-router-dom';
-// import { BrowserRouter as Link } from 'react-router-dom';
+import MUtil from 'util/mutil.jsx';
+
 import './index.scss';
 const SubMenu = Menu.SubMenu;
-// function Logo(props) {
-// 	const { collapsed } = props;
-// 	console.log('collapsed');
-// 	if (props) {
-// 		return <div>123</div>;
-// 	} else {
-// 		return <div>456</div>;
-// 	}
-// }
+const _mutil = new MUtil();
 class Logo extends React.Component {
 	constructor(props) {
 		super(props);
@@ -44,41 +37,32 @@ class SideNav extends React.Component {
 			theme: 'dark',
 			current: '/',
 			// defaultOpen: 'product',
-			myTextInput: ''
+			myTextInput: '',
+			userInfo: _mutil.getStorage('userInfo') || ''
 		};
 	}
 	handleClick(e) {
+		const pathname = this.props.history.location.pathname;
 		this.setState({
 			current: e.key
 		});
-		console.log(this.props.history.location.pathname);
-	}
-	submenuClick(e) {
-		// this.setState({
-		// 	current: e.key
-		// });
+
+		if (pathname !== '/' && this.state.userInfo === '') {
+			_mutil.doLogin();
+		}
 	}
+
 	componentWillMount() {
 		if (this.props.location.pathname !== '/') {
+			if (this.state.userInfo === '') {
+				_mutil.doLogin();
+			}
 			console.log(this.props.location.pathname.split('-')[0]);
 			this.setState({
-				current: this.props.location.pathname,
-				// defaultOpen: this.props.location.pathname.split('-')[0].replace('/', '')
+				current: this.props.location.pathname
 			});
 		}
-
-		// console.log(30);
 	}
-	componentDidMount() {}
-	// print(){
-	// 	console.log(31);
-	// }
-	// 组件的props发生变化,触发该函数
-	// componentDidUpdate(prevProps) {
-	// 	// 监听到数据变化,设置路由数据
-	// 	this.print();
-	// 	// console.log(this.state.current);
-	// }
 	render() {
 		return (
 			<div id="SideNav">

+ 22 - 12
src/component/top-nav/index.jsx

@@ -1,10 +1,27 @@
 import React from 'react';
 import { Menu, Dropdown, Icon } from 'antd';
+import User from 'api/user.jsx';
+import MUtil from 'util/mutil.jsx';
+// import axios from 'axios';
+const _user = new User();
+const _mutil = new MUtil();
 import './index.scss';
 const SubMenu = Menu.SubMenu;
 const MenuItemGroup = Menu.ItemGroup;
+function onLogout() {
+	_user.logout().then(
+		res => {
+			_mutil.removeStorage('userInfo');
+			// window.location.href = '/login';
+			_mutil.doLogin();
+		},
+		errMsg => {
+			_mutil.errorTips(errMsg);
+		}
+	);
+}
 const menu = (
-	<Menu>
+	<Menu onClick={e => onLogout(e)}>
 		<Menu.Item>
 			<Icon type="logout" />
 			退出登录
@@ -17,29 +34,22 @@ export default class TopNav extends React.Component {
 		this.state = {
 			theme: 'dark',
 			current: 'mail',
-			userName: 'admin'
+			userName: _mutil.getStorage('userInfo').username || ''
 		};
 	}
+
 	handleClick() {
 		console.log('click ', e);
 		this.setState({
 			current: e.key
 		});
 	}
-	print() {
-		console.log(29);
-	}
 	render() {
 		return (
-			<Dropdown
-				overlay={menu}
-				onClick={e => {
-					this.print(e);
-				}}
-			>
+			<Dropdown overlay={menu}>
 				<span style={{ color: 'white' }}>
 					<Icon type="user" />
-					&nbsp; 欢迎,{this.state.userName}
+					&nbsp; {this.state.userName ? <span>欢迎,{this.state.userName}</span> : <span>欢迎您</span>}
 					<Icon type="down" />
 				</span>
 			</Dropdown>

+ 8 - 6
src/page/login/index.jsx

@@ -2,7 +2,7 @@
  * @Author: Johnhong9527
  * @Date:   2019-05-25 20:29:31
  * @Last Modified by:   Johnhong9527
- * @Last Modified time: 2019-05-26 14:42:02
+ * @Last Modified time: 2019-05-26 16:28:31
  */
 
 import React from 'react';
@@ -41,23 +41,25 @@ export default class Login extends React.Component {
     if (!checkResult.status) {
       _mutil.errorTips(checkResult.msg);
     } else {
-      const loading = message.loading('正在提交中!', 0);
       _user.login(loginInfo).then(
         res => {
           if (res.msg === '登录成功') {
-            setTimeout(loading, 1300);
             setTimeout(() => {
               message.success('登陆成功,', 0.5).then(() => {
-                window.localStorage.setItem('userInfo', JSON.stringify(res));
+                _mutil.setStorage('userInfo', res.data);
                 message.loading('正在跳转到登录前的页面', 1.5).then(() => {
-                  this.props.history.push('/');
+                  const pathName = _mutil.getUrlParams('redirect');
+                  if (pathName) {
+                    this.props.history.push(pathName);
+                  } else {
+                    this.props.history.push('/');
+                  }
                 });
               });
             }, 1600);
           }
         },
         errMsg => {
-          setTimeout(loading, 10);
           setTimeout(() => {
             _mutil.errorTips(errMsg);
           }, 300);

+ 13 - 8
src/util/http.jsx

@@ -2,9 +2,12 @@
  * @Author: Johnhong9527
  * @Date:   2019-05-25 17:58:36
  * @Last Modified by:   Johnhong9527
- * @Last Modified time: 2019-05-26 14:40:38
+ * @Last Modified time: 2019-05-26 16:29:34
  */
 import axios from 'axios';
+import MUtil from 'util/mutil.jsx';
+import { message } from 'antd';
+const _mutil = new MUtil();
 // 请求列表
 const requestList = [];
 // 取消列表
@@ -58,7 +61,7 @@ axios.interceptors.response.use(
       };
     } else if (response.data.status === 10) {
       // window.ELEMENT.Message.error('认证失效,请重新登录!', 1000);
-      doLogin();
+      _mutil.doLogin();
       return;
     } else {
       return Promise.reject(response.data.msg || response.data.data);
@@ -78,9 +81,12 @@ axios.interceptors.response.use(
 
 const request = function(url, params, config, method) {
   const fd = new FormData();
-  Object.keys(params).forEach(key => {
-    fd.append(key, params[key]);
-  });
+  if (params) {
+    Object.keys(params).forEach(key => {
+      fd.append(key, params[key]);
+    });
+  }
+  const loading = message.loading('正在提交中!', 0);
   return new Promise((resolve, reject) => {
     axios[method](
       url,
@@ -96,9 +102,11 @@ const request = function(url, params, config, method) {
     )
       .then(
         response => {
+          setTimeout(loading, 1300);
           resolve(response);
         },
         err => {
+          setTimeout(loading, 10);
           if (err.Cancel) {
             console.log(err);
           } else {
@@ -119,8 +127,5 @@ const post = (url, params, config = {}) => {
 const get = (url, params, config = {}) => {
   return request(url, params, config, 'get');
 };
-function doLogin() {
-  window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
-}
 
 export { sources, post, get };

+ 31 - 1
src/util/mutil.jsx

@@ -2,17 +2,47 @@
  * @Author: Johnhong9527
  * @Date:   2019-05-26 12:23:53
  * @Last Modified by:   Johnhong9527
- * @Last Modified time: 2019-05-26 14:15:36
+ * @Last Modified time: 2019-05-26 16:25:00
  */
 import { message } from 'antd';
 export default class MUtil {
+  // 前往登录页面
+  doLogin() {
+    window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
+  }
+  // 获取跳转前的path name
   getUrlParams(name) {
     let queryString = window.location.search.split('?')[1] || '',
       reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'),
       result = queryString.match(reg);
     return result ? decodeURIComponent(result[2]) : null;
   }
+  // 错误提示
   errorTips(errMsg) {
     message.error(`${errMsg || '好像哪里不对劲~'}`);
   }
+  // 设置 本地缓存
+  setStorage(name, data) {
+    const typeDate = typeof data;
+    if (typeDate === 'object') {
+      window.localStorage.setItem(name, JSON.stringify(data));
+    } else if (['number', 'string', 'boolean'].indexOf(typeDate) > -1) {
+      window.localStorage.setItem(name, data);
+    } else {
+      this.errorTips('该数据类型不能用于本地存储');
+    }
+  }
+  // 获取 缓存数据
+  getStorage(name) {
+    const data = window.localStorage.getItem(name);
+    if (data) {
+      return JSON.parse(data);
+    } else {
+      return '';
+    }
+  }
+  // 删除 缓存数据
+  removeStorage(name) {
+    window.localStorage.removeItem(name);
+  }
 }

+ 2 - 1
webpack.config.js

@@ -119,7 +119,8 @@ module.exports = {
         // target: 'https://www.baidu.com',
         // pathRewrite: { '^/manage': '' },
         // secure: false
-      }
+      },
+      '/user/logout.do': { target: 'http://adminv2.happymmall.com', changeOrigin: true }
     }
   },
   plugins: [