【问题标题】:React: Axios response loading on Console but not in DOMReact:Axios 响应加载在控制台上但不在 DOM 中
【发布时间】:2021-12-29 04:34:04
【问题描述】:

我正在做一个项目,我只想从 GET 获取 1 个对象(使用 id)。即使使用 React.useState() 和 React.useEffect(),它也能在 console.log 上正确加载,但不能在 DOM 上加载。但它在列表和创建等过程中运行良好...... 我在这里看到了另一个同样的问题,但他们的回答不适用于我的情况...... 所以如果有人能在这里启发我,我将非常感激。


编辑: 而且......在尝试使用另一个api之后,似乎是我正在使用的当前api......我不确定需要完成哪些授权,因为用于列出的GET和用于创建的POST运行良好......是否有任何 axios 授权问题(需要在后端完成)如果不检查它不会显示在 DOM 上? (原项目后端托管在 Heroku 上)


示例代码

api.ts

import axios, { AxiosResponse } from "axios";

axios.defaults.baseURL = "https://url.../api/";

const responseBody = <t>(response: AxiosResponse<t>) => response.data;
const request = {
    get: <t>(url: string) => axios.get<t>(url).then(responseBody),
    post: <t>(url: string, body: {}) => axios.post<t>(url, body).then(responseBody),
    put: <t>(url: string, body: {}) => axios.put<t>(url, body).then(responseBody),
    delete: <t>(url: string) => axios.delete<t>(url).then(responseBody),
};

export default request;

apiArtist.ts

import axios from 'axios';
import { Artist } from "../models/artist";
import request from './api';
const apiArtist = {
    list: () => request.get<Artist[]>("/Artist"),
    add: (data: Artist) => request.post("/Artist", data),
    edit: (data: Artist) => request.put(`/Artist/${data.id}`, data),
    delete: (id: number) => request.delete(`/Artist/${id}`),
    detail: (id: number) => request.get<Artist>(`/Artist/${id}`),
};

try.ts(组件文件)

import React, { useEffect } from 'react'
import { Artist } from '../../models/artist';

export function Try(props:any) {
  const [artist, setArtist] = React.useState<Artist>(new Artist());
  function refreshArtist(id:number){
    apiArtist.detail(id).then((res)=>{
        setArtist(res);
        console.log('i artist:',res); //it shows correctly on Console
    }).catch((err) => console.log(err));
  }

  React.useEffect(()=>{
    refreshArtist(12); //using raw id since I know it should retrieve success
  },[]); // I've also tried here with:
//[artist] //it's like a while true on Console but doesn't update on DOM
//[artist.username] -->executes 2 times like the next 2 ones
//[artist.username===undefined,artist.username===""] (and them alone)
//[artist.username!==undefined,artist.username!==""] (and them alone)
//even without the last param...  React.useEffect(()=>{ ... });
  
  return (<>
      <div>
        <h2>Doing stuff with data</h2>
        {artist.username}  <- it stills doesnt's show up here
        {artist.name} <- neither here
      </div>
  </>)
};

我知道后端运行良好,因为我可以在控制台上检查正确的响应... 但我不知道为什么它不在 DOM 上更新。 (在 {artist.username} 和 {artist.name} 上)

【问题讨论】:

  • 我也尝试过使用 alert(artist);在console.log检查之后,它显示未定义...但刚刚定义...:/
  • 在“try.ts”的第 8 行,您尝试使用 res.data 而不是 res?你确定 res 已经是你想要的数据了吗?
  • 我也想过,但是在第一个文件请求中已经将获得的数据转换为我需要的对象类型。 (而且由于我使用的是打字稿,如果我输入 res. 它会向我显示对象属性,如用户名和名称。)

标签: node.js reactjs typescript react-hooks axios


【解决方案1】:

试试这个

  setArtist(() => res)

【讨论】:

    【解决方案2】:

    您可以尝试创建new Artist() 并从res 加载Artist 并执行setArtist(artist)

    const [artist, setArtist] = React.useState<Artist>(new Artist());
    function refreshArtist(id:number){
        apiArtist.detail(id).then((res)=>{
            let artist = new Artist();
            artist.username = res.username;
            artist.name = res.name;
            setArtist(artist);
            console.log('i artist:',res); //it shows correctly on Console
        }).catch((err) => console.log(err));
    }
    

    【讨论】:

    • 在Artist类中,我默认在字符串上设置“”,在整数上设置0......现在让艺术家=新艺术家();艺术家.用户名 = res.用户名;艺术家.name = res.name;设置艺术家(艺术家); console.log('我艺术家:',艺术家,res);在控制台中, res 仍然可以很好地打印(成功和数据),但现在艺术家.用户名和艺术家.名称未定义......
    • 如果你的资源没问题,并且你将资源中的数据绑定到艺术家,那么它应该没问题。如果不能,请您在codesandbox中准备您的代码吗?这样我就可以运行您的代码并找到问题。
    • OMG 我刚刚尝试过,但使用的是原始 json 文件,因为使用真正的 api 它会显示网络错误(因为授权)并且它可以工作......(codesandbox.io/s/beautiful-dawn-n0y48?file=/src/App.tsx)我要哭了,它只是让我更加沮丧......它与图书馆或其他什么有关吗?我不知道... 依赖项:yarn、react-router-dom、@types/react-router-dom、@mui/material @mui/icons-material、@emotion/react @emotion/styled、@createnl/分组复选框,axios
    • 仍然,谢谢!我只是尝试在真实项目上使用相同的原始文件,它显示得很好......所以,现在我不确定......它必须做一些授权吗?还是本地文件加载速度快还是什么的?...哦...我要检查另一个api,看看是否是这种情况...
    • 不客气 :)
    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 2020-06-28
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多