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

标签 javascript reactjs react-redux react-context

在 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/

相关文章:

javascript - 在不同的 .env 文件中设置 PUBLIC_URL (create-react-app)

reactjs - 为什么当我使用 redux 时 axios.get 不起作用?

javascript - 为什么 JSHint 不显示文件名?

javascript - 使用类似于 onSelect() 的 onChange() 将选择值打印到控制台

reactjs - React Router 中的 props.history.listen 是否需要在 useEffect 中清理?如果是这样,正确的方法是什么?

javascript - 如何在任何调度操作上运行 redux-saga 中间件?

javascript - react : cant handle async function on event

javascript - 如何使 webOS 中的列表看起来像网格?

javascript - Promise.reject() 与返回 promise.reject()

javascript - 仅从 firebase 监听器发送数据是否有效?