当我尝试将酒店对象传递给表单组件时,我的 React TypeScript 应用程序遇到类型错误。错误信息如下:
Type 'HotelType[] | undefined' is not assignable to type 'HotelType'.
Type 'undefined' is not assignable to type 'HotelType'.ts(2322)
ManageHotelForm.tsx(27, 5): The expected type comes from property 'hotel' which is declared here on type 'IntrinsicAttributes & Props'
这些是代码的所有相关部分:
// page.tsx
const EditHotel = () => {
const {hotelId} = useParams();
const {data:hotel} = useQuery("fetchHotelById", ()=> apiClient.fetchHotelById(hotelId || ""),{ enabled: !!hotelId})
return <ManageHotelForm hotel={hotel} />
}
// HotelType.tsx
export type HotelType = {
_id: string;
userId: string;
name: string;
city: string;
country: string
description: string;
type: string;
adultCount: number;
childCount: number;
facilities: string[];
pricePerNight: number;
starRating: number;
imageURLs: string[];
lastUpdated: Date;
}
//管理酒店表格.tsx
type Props = {
onSave: (hotelFormData: FormData)=> void
isLoading: boolean,
hotel: HotelType,
}
const ManageHotelForm = ({onSave,isLoading,hotel}: Props) => {
const formMethods = useForm<HotelFormData>()
const {handleSubmit,reset} = formMethods;
useEffect(()=>{
reset(hotel);
},[hotel,reset]);
//按Id获取酒店
export const fetchHotelById = async (hotelId: string): Promise<HotelType[]> => {
const response = await fetch(`${API_BASE_URL}/api/my-hotels/${hotelId}`, {
credentials: "include"
})
if (!response.ok) {
throw new Error('Error fetching hotels');
}
return response.json();
}
//后端路由
router.get('/:id',verifyToken, async (req:Request,res:Response)=>{
const id = req.params.id.toString();
try {
const hotel = await Hotel.findOne({
_id: id,
userId: req.userId,
});
res.json(hotel);
} catch (error) {
res.status(500).json({message: "Error fetching hotels"})
}
})
代码按预期工作,但 Page.tsx 中的 hotel={hotel} 抛出错误。我是打字稿新手,所以我还不知道如何让它快乐。
const {data:hotel} = // ...
根据
fetchHotelById
,一旦加载,hotel
将是一个HotelType数组。而且由于有一段时间还没有加载,酒店也可以undefined
。
type Props = {
onSave: (hotelFormData: FormData)=> void
isLoading: boolean,
hotel: HotelType,
}
但是 ManageHotelForm 的 props 说它只能采取
HotelType
。它不能与数组一起使用,也不能与未定义一起使用。
如果 ManageHotelForm 无法渲染,需要单个酒店,请务必传入一个。例如:
if (!hotel) {
return <div>Loading...</div>
} else {
return (
<>
{hotel.map(val => (
<ManageHotelForm hotel={val} />
)}
</>
}
另一方面,如果 ManageHotelForm 与数组或
undefined
配合得很好,请更改其 props 上的类型:
type Props = {
onSave: (hotelFormData: FormData)=> void
isLoading: boolean,
hotel: HotelType[] | undefined,
}