javascript - 如何更新所有打开的选项卡中的本地存储

标签 javascript reactjs ecmascript-6 shopping-cart

我将所有数据存储在浏览器本地存储中,并使用名为 Cart 的类来管理本地存储中的数据。

class Cart{
    constructor(){
        this._token = 'fafacart_items';

        this._items = null;


        this._orderId = null;

        this._shipping = {
            id: null,
            city: null,
            type: 'post',
            name: '',
            mobile: '',
            email: '',
            address: '',
            postcode: '',
            national_code: ''
        };

        this._coupon = {
            active: false
        };

        this._paymentMethod = 'online';

        this._validation = null;

        // this.restore();

        window.addEventListener('storage', this.restore())
    }

 restore(){
        var stored = Storage.getItem(this._token);
        console.log(stored)
        if(stored){
            this._items = stored.items;
            this._shipping = Object.assign({}, this._shipping,   stored.shipping);
            this._coupon = Object.assign({}, this._coupon, stored.coupon);
            this._paymentMethod = stored.paymentMethod;
            this._validation = stored.validation;
            this.orderId = stored.orderId;
        } else {
            this._items = [];
        }

        if(this._items.length == 0)
            this.valid = true;
    }


}

我有一个名为 CartHolder 的其他类,它显示本地存储中的所有数据。 它有一个名为 add-to-cart 的监听操作按钮的全局事件 执行此方法后更新浏览器上的本地存储。

export default class CartHolder extends Component {
    constructor(props) {
        super(props);

        this.state = {
            cart: null
        };

        this.restore = this.restore.bind(this);
    }

    componentWillMount(){
        if(this.props.paid){
            Cart.empty();
        }

        this.listen('add-to-cart', product => {
            Cart.add(product);

            this.restore();
        });

        this.restore();
    }

    restore(){
        this.setState({cart: Cart});
    }
}

当本地存储更新时,我看不到之前打开的其他浏览器选项卡上的数据,我只能看到当前选项卡中的数据,刷新其他选项卡后我可以看到它们上的数据。

我想在其他选项卡中查看更新的本地存储数据,而无需刷新或重新加载浏览器选项卡

最佳答案

由于浏览器选项卡位于客户端,唯一可能的方法是刷新所有浏览器选项卡以加载最新的数据。

为此,您可以使用 JS:

browser.tabs.reload();

但是请注意,这是一个新的 JS 函数,目前并非所有浏览器都支持它。请参阅兼容性 here .

关于javascript - 如何更新所有打开的选项卡中的本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176895/

相关文章:

javascript - 不显示特定通知 React Native

css - Material 对话框在打开时将主体滚动到顶部

javascript - React State Hook如何从ES6 Destructuring Assignment中获取状态变量名

JavaScript 动画平滑滚动

javascript - 使用 mapDispatchToProps 映射的操作不带参数

javascript - 为什么在下面的代码片段中调用 'onClick' 的函数应该在另一个箭头函数中调用?

javascript - ES6 NPM RollUp.Js 回调失败

javascript - 对象中嵌套数组的 Angular ng-repeat 过滤器

javascript - 相机可以是纹理吗?

javascript - 如何修复 jQuery 中不稳定的动画