英文:
Trying to assign a response.data value to a variable in react and the value doesnt pass well
问题
我正在React中构建一个AuthContext来处理登录,将其连接到一个Django后端,在那里验证用户,然后获取授权令牌。
import React, { createContext, useState, useEffect } from 'react';
import axios from 'axios';
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
  const [token, setToken] = useState(null);
  const login = async (username, password) => {
    try {
      const response = await axios.post('http://127.0.0.1:8000/token/', {
        username,
        password
      });
      console.log('Response data:', response.data);
      const { token: responseToken } = response.data;
      setToken(responseToken);
      console.log('Token loaded:', responseToken);
    } catch (error) {
      console.error('Error en el inicio de sesión:', error);
    }
  };
  useEffect(() => {
    console.log('Token actual value:', token);
  }, [token]);
  return (
    <AuthContext.Provider value={{ token, login }}>
      {children}
    </AuthContext.Provider>
  );
};
从我的后端获取了预期的响应,状态码200以及我期望的令牌,但在将response.data分配给responseToken之后,在下一个日志中显示为未定义。这是在浏览器控制台中的输出:
尝试更改变量名称以检查是否存在与已声明的变量之间的冲突,但问题仍然存在。
英文:
Im building an AuthContext in react to handle login, i connect it to a django backend where i validate the user and then i get an authorization token
import React, { createContext, useState, useEffect} from 'react';
import axios from 'axios';
export const AuthContext = createContext();
  export const AuthProvider = ({ children }) => {
    const [token, setToken] = useState(null);
  
    const login = async (username, password) => {
      try {
        const response = await axios.post('http://127.0.0.1:8000/token/', {
          username,
          password
        });
        console.log('Response data:', response.data);
        const { token: responseToken } = response.data;
        setToken(responseToken);
    
        console.log('Token loaded:', responseToken);
      } catch (error) {
        console.error('Error en el inicio de sesión:', error);
      }
    };    
  
    useEffect(() => {
      console.log('Token actual value:', token); 
    }, [token]);
  
    return (
      <AuthContext.Provider value={{ token, login }}>
        {children}
      </AuthContext.Provider>
    );
  };
From my backend i get the expected answer, an status 200 with the token that i expect, but after assign the response.data to responseToken, in the next log it shows that is undefined. Here is the output in the navigator console:
Tried to change the variable names to check if there is a conflict between those declared there, but the problem persists.
答案1
得分: 0
你的控制台日志显示响应数据有两个属性 refresh 和 access。但是你尝试获取一个叫做 token 的属性,这个属性并不存在(或者至少在你的截图中看不到)。
const { access: responseToken } = response.data;
这应该有所帮助(如果 access 是你实际需要的属性的话)。
英文:
Your console log shows that response data has two properties refresh & access. But you are trying to get a property called token, which does not exist (or at least it's not visible in your screenshot).
const { access: responseToken } = response.data;
This should help. (if access is the one you actually need)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论