我目前有这个功能:
const fetchJobs = async (userId: string) => {
setJobs([])
await axios.post("/api/fetch/fetchMany?type=jobs", {
user_id: userId
})
.then((response) => {
if (response == null || response.data.length === 0) {
setJobs([])
} else {
const sortedJobs = response.data.sort = (a: Date, b: Date): Job[] => {
return new Date(a.startDate) - new Date(b.startDate)
}
setJobs(sortedJobs)
}
})
}
它所做的是获取一个"作业"对象列表,然后尝试将它们从最新到最旧排序,然后将它们放入作业状态。
然而,有两个问题:
- 我正在获取排序函数中类型"Date"上不存在"startDate">
- 该函数不可分配给类型为"SetStateAction<作业[]>'
对于某些上下文,这里是我的作业类型,它是一个对象数组:
export type Job = {
_id: string,
user_id: string,
jobTitle: string,
employer: string,
responsibilities: string[],
startDate: string | Date,
endDate: string
}
然后是我的状态类型:
const [jobs, setJobs] = useState<Job[]>([])
我想我需要更改我的状态可以设置为什么,但我不明白为什么我不能使用函数设置状态,因为它返回一组作业类型。
如有任何帮助,将不胜感激
键入axios请求await axios.post<Job[]>(...)
,以便相应地自动键入response.data
。
数组#sort()是一个方法,而不是属性。它期望一个回调函数从数组中接收两个值(在您的情况下,这两个值的类型是Job
,而不是Date
),并根据它们的顺序返回一个带符号的数字。不是布尔值response.data.sort((a, b) => new Date(a.startDate) - new Date(b.startDate))
不要把async/await
和.then()
混在一起
所以整个
const fetchJobs = async (userId: string) => {
setJobs([])
const response = await axios.post<Job[]>("/api/fetch/fetchMany?type=jobs", {
user_id: userId
});
if (!response || response.data.length === 0) {
// setJobs([]) // you've already done that
return;
}
const sortedJobs = response.data.sort((a, b) => new Date(a.startDate) - new Date(b.startDate));
setJobs(sortedJobs);
}
在处理network tasks
时使用async/await
或Promise
const fetchJobs = async (userId: string) => {
setJobs([]) // Initailly set to null
const response = await axios.post<Job[]>("/api/fetch/fetchMany?type=jobs", {
user_id: userId
});
if (!response || response.data.length === 0) {
return; // return here instead of using if/else
}
// Change the sort method by specifying the types
const sortedJobs = response.data.sort((a: Job, b: Job): number => new Date(a.startDate) - new Date(b.startDate));
setJobs(sortedJobs); // set the sorted Jobs here
}
第一期:
我得到了排序函数中类型"Date"上不存在的"startDate">
您可以更改中排序参数的类型
const sortedJobs = response.data.sort = (a: Date, b: Date): Job[] => {
return new Date(a.startDate) - new Date(b.startDate)
}
至
const sortedJobs = response.data.sort((a: Job, b: Job): number => {
return new Date(a.startDate).getTime() - new Date(b.startDate).getTime()
})
如果它解决了第二个问题,请告诉我,因为我找不到的问题
函数不可分配给'SetStateAction<作业[]>'
但此更改可能同时修复了两者。