daily-share icon indicating copy to clipboard operation
daily-share copied to clipboard

项目代码更新提醒(2021-9-9)

Open yaogengzhu opened this issue 3 years ago • 0 comments

需求背景:

  • 每当前端更改代码,测试总是反馈还有bug,我明明已经改好了,还要通知测试刷新页面,好累喔!
  • 用户不能及时刷新获取最新功能代码
import React from 'react';
import axios from 'axios';
import { notification, Button } from 'antd';

const CRMSYSTEMFRONTVERSION = 'crmSystemFrontVersion';
function CheckHash() {
    this.uploadNotificationShow = false; // 判断可以弹框
    this.close = () => {
        this.uploadNotificationShow = false;
    };
    this.onRefresh = (newHash) => {
        this.close();
        window.localStorage.setItem(CRMSYSTEMFRONTVERSION, newHash);
        window.location.reload(true);
    };

    this.openNotification = (newHash) => {
        this.uploadNotificationShow = true;
        const btn = (
            <Button
                type="primary"
                onClick={() => {
                    return this.onRefresh(newHash);
                }}
            >
                确认更新
            </Button>
        );
        notification.open({
            message: '版本更新提示',
            description: '检测到系统当前版本已更新,请刷新后使用。',
            btn,
            duration: 0, // 不自动关闭
            onClose: close,
        });
    };

    /**
     * 可以返回当前的hash
     * @returns
     */
    this.getNewHash = () => {
        return new Promise((resolve, reject) => {
            return axios
                .get(`${window.location.origin}/index.html?time=${new Date().getTime()}`)
                .then((res) => {
                    // 匹配index.html文件中引入的js文件是否变化
                    const newHash = (res.data && res.data.match(/\/scripts\/vendors.(.*).js/)[1]) || null;
                    const oldHash = localStorage.getItem(CRMSYSTEMFRONTVERSION);
                    if (!oldHash) {
                        this.openNotification(newHash);
                    }
                    if (oldHash && oldHash !== newHash) {
                        this.openNotification(newHash);
                    }
                    resolve(newHash);
                })
                .catch((e) => {
                    reject(e);
                });
        });
    };
}

const checkHash = new CheckHash();
export default checkHash;

用法

...
...
componentDidMount() {
        checkHash.getNewHash();
        this.timerId = setInterval(() => {
            checkHash.getNewHash(); // 5分钟检测一次
        }, 50000);
    }

componentWillUnmount() {
    clearInterval(this.timerId);
}
...

yaogengzhu avatar Sep 09 '21 02:09 yaogengzhu