存储用户 ID 的最佳解决方案是什么?
What's the best solution for storing a users id?
在 ReactJS 中存储用户 ID 以便所有组件都可以访问它的最佳方法是什么?
我已经研究过 Redux 和 Context,但它们似乎只是存储 ID 太过分了(或者我可能遗漏了什么?)。我也看过将 ID 存储在父组件 (App) 中,但页面刷新会丢失 ID :(.
会话存储可能最适合您的需求
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
然后您可以在需要时set/get 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');
如果您希望您的数据在关闭并重新打开浏览器后仍然可用,LocalStorage 是存储数据的合适位置;否则,只要浏览器打开,SessionStorage 就会保留您的数据。
将诸如用户 ID 之类的敏感数据保存在存储中是个坏主意!
每次用户硬刷新 his/her 浏览器时,您都需要获取此数据。请勿使用存储来节省此类费用!
在 ReactJS 中存储用户 ID 以便所有组件都可以访问它的最佳方法是什么?
我已经研究过 Redux 和 Context,但它们似乎只是存储 ID 太过分了(或者我可能遗漏了什么?)。我也看过将 ID 存储在父组件 (App) 中,但页面刷新会丢失 ID :(.
会话存储可能最适合您的需求
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
然后您可以在需要时set/get 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');
如果您希望您的数据在关闭并重新打开浏览器后仍然可用,LocalStorage 是存储数据的合适位置;否则,只要浏览器打开,SessionStorage 就会保留您的数据。
将诸如用户 ID 之类的敏感数据保存在存储中是个坏主意! 每次用户硬刷新 his/her 浏览器时,您都需要获取此数据。请勿使用存储来节省此类费用!