【发布时间】: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