尝试将 response.data 的值分配给 React 中的变量,但该值未成功传递。

huangapple go评论53阅读模式
英文:

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之后,在下一个日志中显示为未定义。这是在浏览器控制台中的输出:

console logs

尝试更改变量名称以检查是否存在与已声明的变量之间的冲突,但问题仍然存在。

英文:

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 &#39;react&#39;;
import axios from &#39;axios&#39;;

export const AuthContext = createContext();


  export const AuthProvider = ({ children }) =&gt; {
    const [token, setToken] = useState(null);
  
    const login = async (username, password) =&gt; {
      try {
        const response = await axios.post(&#39;http://127.0.0.1:8000/token/&#39;, {
          username,
          password
        });
        console.log(&#39;Response data:&#39;, response.data);
        const { token: responseToken } = response.data;
        setToken(responseToken);
    
        console.log(&#39;Token loaded:&#39;, responseToken);
      } catch (error) {
        console.error(&#39;Error en el inicio de sesi&#243;n:&#39;, error);
      }
    };    
  
    useEffect(() =&gt; {
      console.log(&#39;Token actual value:&#39;, token); 
    }, [token]);
  
    return (
      &lt;AuthContext.Provider value={{ token, login }}&gt;
        {children}
      &lt;/AuthContext.Provider&gt;
    );
  };

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:

console logs

Tried to change the variable names to check if there is a conflict between those declared there, but the problem persists.

答案1

得分: 0

你的控制台日志显示响应数据有两个属性 refreshaccess。但是你尝试获取一个叫做 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)

huangapple
  • 本文由 发表于 2023年6月2日 03:20:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定