我目前正在 React 中學習 TypeScript,所以我正在學習如何使用 typescript 發出 API 請求屬性不存在這里是我的代碼
import { To, useParams } from "react-router-dom";
import axios from "axios";
import { useState, useEffect } from "react";
const SinglePOST = () => {
type Todo = {
title: string;
body: string;
userId: number;
id: number;
};
const { id } = useParams();
const [data, setData] = useState<Todo[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [isError, setError] = useState<any>(null);
useEffect(() => {
const singleReq = async () => {
try {
setLoading(true);
const res = await axios.get<Todo[]>(
`https://jsonplaceholder.typicode.com/posts/${id}`,
);
await setData(res.data);
console.log(res.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
singleReq();
}, [id]);
return (
<div className=' w-full h-screen bg-slate-900 text-neutral-300 p-4'>
<div className='w-full flex justify-center '> Single Post {id}</div>
{loading && <p>...Loading</p>}
{isError && <p> Error in getting post</p>}
<div className='text-2xl'> {data.title}</div>
<div className=' text-xl'> {data.body}</div>
</div>
);
};
export default SinglePOST;
這是它顯示的錯誤
型別“Todo []”上不存在屬性“標題”
型別“Todo []”上不存在屬性“body”
uj5u.com熱心網友回復:
因為您的資料是單個物件,但您將資料定義為物件串列。
import { To, useParams } from 'react-router-dom';
import axios from 'axios';
import { useState, useEffect } from 'react';
const SinglePOST = () => {
type Todo = {
title: string;
body: string;
userId: number;
id: number;
};
const { id } = useParams();
const [data, setData] = useState<Todo>();
const [loading, setLoading] = useState<boolean>(false);
const [isError, setError] = useState<any>(null);
useEffect(() => {
const singleReq = async () => {
try {
setLoading(true);
const res = await axios.get<Todo>(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
await setData(res.data);
console.log(res.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
singleReq();
}, [id]);
return (
<div className=' w-full h-screen bg-slate-900 text-neutral-300 p-4'>
<div className='w-full flex justify-center '> Single Post {id}</div>
{loading && <p>...Loading</p>}
{isError && <p> Error in getting post</p>}
<div className='text-2xl'> {data?.title}</div>
<div className=' text-xl'> {data?.body}</div>
</div>
);
};
uj5u.com熱心網友回復:
您已將型別設定為您的狀態作為 Todo 物件串列,因此出現錯誤。
const [data, setData] = useState<Todo[]>([]);
您的 get 請求是否回傳一系列待辦事項?如果是,那么您需要通過它們進行映射:
{
data.map((todo, idx) => {
return (
<div key={idx}>
<div className='text-2xl'> {data.title}</div>
<div className=' text-xl'> {data.body}</div>
</div>
)
});
}
如果您的 get 請求回傳一個 todo 物件,那么您需要更改狀態的型別:
const [data, setData] = useState<Todo>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508000.html
標籤:javascript 反应 打字稿 反应打字稿
