React 使用Context实现全局状态管理

1、用户登陆和信息: context/auth-context.tsx:

import React, { createContext, useContext, useState, useEffect } from 'react';
import { useCookies } from 'react-cookie';
import { fetchUserData } from '../api/user';
import { User } from '../types/user';

interface AuthContextType {  //输出的接口类型
  isLoggedIn: boolean;
  user: User | undefined;
  login: () => void;
  logout: () => void;
}

// 1、创建context实例
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// Provider包裹其他组件
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState<User | undefined>(undefined);
  const [cookies] = useCookies(['__csrf']);

  const getUser = () => {
    fetchUserData()
      .then((res) => {
        console.log(res.data);
        setUser(res.data.profile || undefined);
      })
      .catch((error) => {
        console.error('Failed to fetch user data:', error);
      });
  };
  useEffect(() => {
    // 检查用户是否已登录
    setIsLoggedIn(!!cookies['__csrf']);

    // 如果已登录,则获取用户数据
    if (!!cookies['__csrf']) {
      getUser();
    }
  }, []);

  const login = () => {
    // 设置用户数据和登录状态
    getUser();
    setIsLoggedIn(true);
  };

  const logout = () => {
    // 清空用户数据和登录状态
    setUser(undefined);
    setIsLoggedIn(false);
  };

// 返回context
  return (
    <AuthContext.Provider value={{ isLoggedIn, user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

// 其他组件调用的函数useAuth
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

2、index.tsx: 包裹app组件

 <AuthProvider>
  <Provider store={store}>
    <App />
  </Provider>
</AuthProvider>

3、其他组件使用:

const { user } = useAuth();

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值