You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Context API存储登录后API返回的userId与username

问题描述

在React项目中,需要用Context API存储登录成功后API返回的userId和username,实现全局复用。已搭建LoginContext、App.js和LoginAdmin.js基础结构,但无法从Axios响应中成功存储用户信息。

解决方案

核心问题是你在获取用户详情的接口响应后,未调用Context提供的setUser方法存储数据。按以下方式修改即可:

1. 存储用户信息到Context

在第二个Axios请求(获取用户详情)的成功回调中,从响应数据里提取userId和username,通过setUser存入Context。另外,登录接口已返回userId,如果业务允许,也可以直接结合输入的username存储,减少一次接口调用。

修改后的LoginAdmin.js代码

// React
import { useNavigate } from "react-router-dom";
import { useState, useContext } from "react";
import { Link } from "react-router-dom";

// Axios
import axios from "axios";

// Context
import { LoginDataContext } from "../Contexts/LoginContext";

// Logo
import DyreLogo from "../assets/logo.png";

// Icons
import { HiArrowNarrowLeft } from "react-icons/hi";

const AdminLogin = ({setToken}) => {
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [badLogin, setBadLogin] = useState(false);
const { user, setUser} = useContext(LoginDataContext)

let navigate = useNavigate();

function handleLogin(e) {
e.preventDefault();
setIsLoggingIn(true);
setBadLogin(false);
const form = e.target;
const username = form[0].value;
const password = form[1].value;

    axios
      .post("http://localhost:4000/auth/token", {
        username: username,
        password: password,
      })
      .then((response) => {
        if (response.status === 200) {
          const { token, userId } = response.data;
          setToken(token);
          
          // 方案1:直接用登录接口返回的userId + 输入的username存储(减少接口调用)
          // setUser({ userId, username });

          // 方案2:调用用户详情接口获取完整信息后存储
          axios
            .get(`http://localhost:4000/api/v1/users/${userId}`, {
              headers: { Authorization: `Bearer ${token}` },
            })
            .then((userResponse) => {
              if (userResponse.status === 200) {
                // 根据接口实际返回字段调整解构内容
                const { userId, username } = userResponse.data;
                setUser({ userId, username });
                setIsLoggingIn(false);
                navigate("/Dashboard");
              }
            });
        }
      })
      .catch((error) => {
        setIsLoggingIn(false);
        setBadLogin(true);
      });

}
return (
<div className="flex justify-center items-center flex-col h-screen bg-gray-200">
<img
 src={DyreLogo}
 alt="Logo of hands holding a dog"
 className="w-28 h-28 border-4 border-blue-600 p-2 rounded-full"
 />
<form
 className="bg-white flex flex-col gap-10 w-[28rem] px-28 pb-24 pt-10 mt-10 rounded-md shadow-md"
 onSubmit={handleLogin}
 >
<div>
<h2>Brugernavn</h2>
<input
 className="bg-gray-300 rounded-sm w-full p-2 mt-2 outline-none"
 type="text"
 />
</div>
<div>
<h2>Adgangskode</h2>
<input
 className="bg-gray-300 rounded-sm w-full p-2 mt-2 outline-none"
 type="password"
 />
</div>
{badLogin && (
<div className="bg-red-500 text-white text-center visible rounded-sm">Brugernavn eller adganskode var forkert</div>
)}
<button className="p-2 px-3 bg-blue-600 rounded-sm text-white w-full">
{!isLoggingIn ? "Log ind" : "Logger ind"}
</button>
<Link to="/">
<div className="flex items-center gap-2">
<HiArrowNarrowLeft className="w-5 h-5" />
<p>Hjem</p>
</div>
</Link>
</form>
</div>
);
};

export default AdminLogin;

2. 在其他组件中使用用户信息

比如在AdminDashboard中,通过useContext获取用户数据:

import { useContext } from "react";
import { LoginDataContext } from "../Contexts/LoginContext";

const AdminDashboard = ({ token }) => {
  const { user } = useContext(LoginDataContext);
  
  return (
    <div>
      <h1>欢迎,{user?.username}</h1>
      <p>你的用户ID:{user?.userId}</p>
    </div>
  );
};

export default AdminDashboard;

注意:需确保用户详情接口返回的字段与代码中解构的userId、username一致,若字段名不同(比如id代替userId),需对应修改变量名。

内容的提问来源于stack exchange,提问作者Daniel707

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:50:43