无法在移动浏览器上检索会话存储 [英] Session Storage not being retrieved on mobile browser

查看:48
本文介绍了无法在移动浏览器上检索会话存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 create-react-app,我在 sessionStorage 中存储了一些状态,以便在用户会话期间保留一些 redux 状态.

I have a create-react-app and I'm storage some state inside of sessionStorage to persist some redux state during the user's session.

在桌面浏览器中一切正常,但在 Safari 或 Chrome 中的移动设备上调试时,刷新时无法检索状态.这会导致错误,因为状态不再存在.

Everything works fine in Desktop browsers but while debugging on a mobile device inside of Safari or Chrome the state isn't be retrieved on refresh. This causes errors since the state is no longer there.

知道为什么这只会发生在移动浏览器上吗?

这就是我使用 sessionStorage 保存和检索状态的方式:

This is how I'm saving and retrieving the state with sessionStorage:

export function saveToLocalStorage(state: AppState) {
    const hasUserProfileId =
        state.system.profile.id && state.system.profile.id !== '';
    try {
        if (hasUserProfileId) {
            const serializedState = JSON.stringify(state);
            sessionStorage.setItem('state', serializedState);
        }
    } catch (error) {
        console.log('Error saving state to local storage');
    }
}

function loadFromLocalStorage() {
    console.log('loadFromLocalStorage - 1');

    try {
        const serializedState = sessionStorage.getItem('state');

        if (serializedState === null) {
            return undefined;
        }
        return JSON.parse(serializedState);
    } catch (error) {
        console.log('Error loading state from local storage');
        return undefined;
    }
}

在执行 const serializedState = sessionStorage.getItem('state'); 时为 null,所以它返回 undefined

its null when doing const serializedState = sessionStorage.getItem('state'); so it returns undefined

if (serializedState === null) {
     return undefined;
 }

推荐答案

我使用 beforeunload 事件侦听器来保存刷新状态.移动浏览器不支持此事件处理程序.用 unload 替换它有效.

I was using beforeunload event listener to save the state on refresh. This event handler wasn't supported for mobile browsers. Replacing it with unload worked.

window.addEventListener('unload', () => {
     saveToLocalStorage(store.getState());
});

这篇关于无法在移动浏览器上检索会话存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆