简体   繁体   English

React Native 中是否有与 sessionStorage 等价的东西?

[英]Is there an equivalent to sessionStorage in React Native?

I'd like to implement the equivalent to the javascript sessionStorage and localStorage in my React Native app.我想在我的 React Native 应用程序中实现与 javascript sessionStorage 和 localStorage 等效的功能。 I have localStorage sorted with the React Native AsyncStorage component.我使用 React Native AsyncStorage 组件对 localStorage 进行了排序。 But I'm unsure how to replicate sessionStorage.但我不确定如何复制 sessionStorage。 To function how I want it to, I would like the sessionStorage to be cleared every time the app closes.对于 function 我希望它如何,我希望每次应用程序关闭时都清除 sessionStorage。 Is there a way to do this?有没有办法做到这一点?

You can store things in a central state, using like Context API or redux .您可以使用Context APIredux类的方式将内容存储在中央 state 中。 I think that would be the best alternate for session.我认为这将是 session 的最佳替代品。

If your using typescript you could store this file somewhere in your project name it something like "Storage.tsx"如果您使用 typescript 您可以将此文件存储在项目名称中的某个位置,例如“Storage.tsx”

declare module globalThis {
    let sessionStorage: Storage;
}

class Storage {
    private data: Map<string, any>;

    constructor() {
        this.data = new Map<string, any>();
    }

    public key(n: number) {
        return [...this.data.keys()][n];
    }
    public getItem(key: string) {
        return this.data.get(key);
    }
    public get length() {
        return this.data.size;
    }

    public setItem(key: string, value: any) {
        this.data.set(key, value);
    }
    public removeItem(key: string) {
        this.data.delete(key);
    }
    public clear() {
        this.data = new Map<string, any>();
    }
    
}

let sessionStorage = globalThis.sessionStorage = globalThis.sessionStorage ?? new Storage();

export { Storage, sessionStorage };

If your using regular javascript store it as "Storage.jsx"如果您使用常规 javascript 将其存储为“Storage.jsx”

class Storage {
    constructor() {
        this.data = new Map();
    }

    key(n) {
        return [...this.data.keys()][n];
    }
    getItem(key) {
        return this.data.get(key);
    }
    get length() {
        return this.data.size;
    }

    setItem(key, value) {
        this.data.set(key, value);
    }
    removeItem(key) {
        this.data.delete(key);
    }
    clear() {
        this.data = new Map();
    }
    
}

let sessionStorage = globalThis.sessionStorage = globalThis.sessionStorage ?? new Storage();

export { Storage, sessionStorage };

I know this is an late answer but could work for other people stumbling on this post.我知道这是一个迟到的答案,但可以为其他绊倒这篇文章的人工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM