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

SE_*_*991 1 javascript reactjs react-redux react-context

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

我已经研究过 Redux 和 Context,但它们似乎只是存储一个 ID(或者我可能遗漏了什么?)。我还研究了将 ID 存储在父组件 (App) 中,但页面刷新会丢失 id :(。

Mar*_*ark 5

会话存储可能最适合您的需求

sessionStorage 属性允许您访问当前源的会话存储对象。sessionStorage 类似于 localStorage;唯一的区别是 localStorage 中存储的数据没有过期时间, sessionStorage 中存储的数据在页面会话结束时被清除。

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

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

sessionStorage.setItem('userID', 'value');
const USER_ID = sessionStorage.getItem('userID');
Run Code Online (Sandbox Code Playgroud)

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

只读 localStorage 属性允许您访问文档来源的 Storage 对象;存储的数据跨浏览器会话保存。localStorage 与 sessionStorage 类似,不同之处在于虽然 localStorage 中存储的数据没有过期时间,但 sessionStorage 中存储的数据会在页面会话结束时(即页面关闭时)被清除。

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

localStorage.setItem('userID', 'value');
const USER_ID = localStorage.getItem('userID');
Run Code Online (Sandbox Code Playgroud)