logo

该视频仅会员有权观看

立即开通课程「Next.js 前端应用开发实践」权限。

¥
199
/ 年

恢复用户的登录状态

  • After successful business login, user data can be stored in the browser's local storage to maintain user login state upon application refresh.
  • Two methods are defined: setStorage to set local storage with a key (string) and value (any), and getStorage to retrieve local storage data using a key (string).
  • setStorage uses localStorage.setItem to save data, with value processed by JSON.stringify.
  • getStorage may return the data processed by JSON.parse if present or null otherwise.
  • A constant STORAGE_KEY with currentUser property is exported for consistent data naming during storage and retrieval.
  • A LoginProvider component utilizes useEffect to react to currentUser changes, storing or retrieving user data as necessary.
  • Local storage gets tested in the browser's developer tools, demonstrating appearance and retrieval of currentUser data, which includes the user's ID, name, and token.
  • Upon page refresh and application reload, the saved currentUser data is read from local storage and used to restore the user's login state.
  • The current user's name is displayed at the top of the page, reflecting the logged-in status.