gpt4 book ai didi

javascript - 存储用户 ID 的最佳解决方案是什么?

转载 作者:行者123 更新时间:2023-11-30 08:20:09 25 4
gpt4 key购买 nike

在 ReactJS 中存储用户 ID 的最佳方法是什么,以便所有组件都可以访问它?

我已经研究过 Redux 和 Context,但它们似乎对于仅存储 ID(或者我可能遗漏了什么?)来说太过分了。我还研究过将 ID 存储在父组件 (App) 中,但页面刷新会丢失 ID :(。

最佳答案

session 存储可能最适合您的需求

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to localStorage; the only difference is while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends.

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

然后您可以在需要时设置/获取 ID

sessionStorage.setItem('userID', 'value');
const USER_ID = sessionStorage.getItem('userID');

但是,要在页面关闭后保留 ID,您需要使用 localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

localStorage.setItem('userID', 'value');
const USER_ID = localStorage.getItem('userID');

关于javascript - 存储用户 ID 的最佳解决方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54790135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com