【发布时间】:2021-04-24 05:39:10
【问题描述】:
我正在尝试在 React 中使用 TypeScript,但遇到了一个我不明白的错误:
<html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction<User>'.<br/>Property 'subEnd' does not exist on type '(prevState: User) => User'.
我正在尝试在我使用useState 设置的对象的方法中使用this,但出现错误:
function fetchUserInfo(
data: InterfaceJsonUserInfo,
setUserObject: React.Dispatch<React.SetStateAction<User>>
) {
setUserObject({
id: data.id,
subEnd: new Date(data.subEnd),
subExpired() {
const subEndDate = this.subEnd;
const nowDate = new Date();
return (subEndDate > nowDate);
},
}
这是我的界面:
export interface User {
id: string, // Uuid
subEnd: Date,
subExpired: () => boolean,
}
我不明白为什么会收到错误消息,因为 subEnd 在用户界面上。
当我从<User> 更改为 React.Dispatch<React.SetStateAction<any>> 时,代码确实有效,但我想指定类型而不是使用any。那我做错了什么?
【问题讨论】:
标签: javascript reactjs typescript object setstate