背景:
在同一浏览器登录A用户之后。此时打开新标签页面,在登录B用户。此时因为A用户的登录信息已经被B用户更新,造成数据不正确,提出了这样了的一个问题。
我们给的解决方法是:登录用户B之后,在切换回A用户的浏览器页签的时候,我们会提示已经有新用户登录,然后重新刷新页面。
代码实现
提供一个npm方法,供项目组使用,在登录拿到用户信息之后,调用方法即可。当然这个前提是用户信息依赖于localStorage本地缓存。
export default (storageKeyString: string, seconds: number = 2, tipsCallFunction?: () =>{}) => {
if (typeof seconds !== 'number' ) throw new Error('seconds should be number');
let cacheValue = getStorageVale(storageKeyString);
if (document.hidden !== undefined) {
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
let currentValue = getStorageVale(storageKeyString);
if (currentValue !== cacheValue) {
if (tipsCallFunction && typeof tipsCallFunction === 'function') {
tipsCallFunction();
} else {
window.alert('检测新用户登录,当前页面会在2s之后刷新!');
}
setTimeout(() => {
window.location.reload();
}, seconds * 1000)
}
}
})
}
}
function getStorageVale (storageKeyString: string) {
var [localstorage, ...restKeyArrays] = storageKeyString.split('.');
let localStorageInfo = window.localStorage.getItem(localstorage)
if (!restKeyArrays.length) return localStorageInfo;
let returnVal = JSON.parse(localStorageInfo || '{}');
for(let i = 0; i < restKeyArrays.length; i++ ) {
returnVal = returnVal[restKeyArrays[i]]
if (!returnVal) return '';
if (typeof returnVal === 'string') {
return returnVal
}
}
return ""
}
复制代码
使用方法:
安装使用
npm install --save @bit-sun/business-component@1.1.0
复制代码
代码demo
import React, { useRef } from 'react';
import { message } from 'antd';
import { CheckOneUser } from '@bit-sun/business-component';
CheckOneUser('userInfo.a.information.name', 3, () => {
message.warning('检测新用户登录,当前页面会在3s之后刷新!');
})
export default () => {
return (
<div>
</div>
);
};
复制代码
属性说明
CheckOneUser(
storageKeyString: string,
seconds: number = 2,
tipsCallFunction?: () =>{}
)
复制代码
属性名 | 类型 | 默认值 |
---|---|---|
storageKeyString | string: 'userInfo.a.information.name' | 无 |
seconds | number | 2 |
tipsCallFunction | function | () => { window.alert('检测新用户登录,当前页面会在2s之后刷新!') } |
storageKeyString说明
'userInfo.a.information.name':user为item名称,其他为属性访问
演示demo
demo代码效果展示