例如登录后存储当前登录用户的信息:id
那么总不能用到的时候每次都去请求,那么 useContext
是不是用来解决这个问题的,还有有更好的解决方案?不懂
用 useContext 和 useReducer 或者 useState,轻量级的解决方案:const UserContext = React.createContext(); function UserProvider({ children }) { const [user, setUser] = useState(null); return ( <UserContext.Provider value={{ user, setUser }}> {children} </UserContext.Provider> ); } function useUser() { const context = useContext(UserContext); if (!context) { throw new Error(“useUser must be used within a UserProvider”); } return context; } // 在组件里用 function Profile() { const { user } = useUser(); return <div>{user.id}</div>; }
或者用 MobX:import { observable } from ‘mobx’; import { observer } from ‘mobx-react’; class UserStore { @observable user = null; } const userStore = new UserStore(); const Profile = observer(() => ( <div>{userStore.user.id}</div> ));
除了使用 Redux
等状态管理,还可以使用黑科技,将全局变量储存到 window
或 globalThis
对象上:window.globalState = {}; globalState.id = id;
但是这样还不能持久化,页面刷新变量会重新赋值,id
也需要重新请求。还需要配合 localStorage
和 sessionStorage
将状态保存下来。
你可以将这个 globalState
封装好,暴露 getGlobalValue
和 setGlobalValue
方法;
注意,只有当数据比较少的时候可以使用这种方式,如果数据比较多,状态比较复杂,还是应该用状态管理。
简单一点可以挂在window上,但是数据更新时,就无法自动渲染。
如果要使用状态管理库,我推荐使用zustand,原生支持hook写法,简单快速。
根据你的需求,首先我们导出了一个名为 useUserStore 的函数,该函数使用 create 方法创建了一个新的状态存储。该存储包含一个 currentUser 属性和一个 setCurrentUser 方法,用于设置当前登录用户。import create from ‘zustand’ export const useUserStore = create((set) => ({ currentUser: null, setCurrentUser: (user) => set(() => ({ currentUser: user })), }))
在组件中使用 store:import { useUserStore } from ‘./userStore’ function UserInfo() { const { currentUser } = useUserStore() return ( <div> <p>User ID: {currentUser.id}</p> <p>User Name: {currentUser.name}</p> </div> ) }回复