【问题标题】:props does not exist on type PropType类型 PropType 上不存在道具
【发布时间】:2022-02-07 14:24:24
【问题描述】:

我有一个从父组件传递的道具(“作者”)。我输入了 propType("AuthorProps") 但它说 Property 'author' does not exist on type 'AuthorProps' 即使结构看起来一样。

作者属性:

export type AuthorProps = {
  _id: string;
  name: string;
  slug: string;
  authorId:string;
  img: string;
  createdAt?: string;
  updatedAt?: string;
  __v?: number;
}

记录作者道具:

{
    _id: "61ffff139d0ad2a68738843a",
    name: "Chetan Bagat",
    slug: "chetan-bagat",
    authorId: "0",
    img: "https://img.etimg.com/thumb/msid-66099431,width-650,imgsize-149367,,resizemode-4,quality-100/chetan-bhagats-advice-for-students-its-all-about-knowing-how-to-market-yourself.jpg",
    createdAt: "2022-02-06T17:02:11.490Z",
    updatedAt: "2022-02-06T17:02:11.490Z",
    __v: 0
}

组件:

function AuthorContainer({ author }: AuthorProps) { // }

【问题讨论】:

  • 你好像有authorId,但没有author
  • @是的,你可以看到上面的作者对象。
  • { author }: AuthorProps 替换为{ author }: { author: AuthorProps }
  • @iz_ 谢谢,成功了!但是我的方式有什么问题?我们通常这样使用它对吗?
  • { author }: AuthorProps 表示{ author }AuthorProps 类型,但它不是。你的道具的形状是{ author: AuthorProps }{ author: { _id: string; name: string; ... } }

标签: reactjs typescript next.js


【解决方案1】:

在您的组件中,您使用object destructuring 并尝试从AuthorProps 获取{author}AuthorProps 的定义不包含该属性。

您可能希望将代码更改为如下内容:

export type AuthorProps = {
  author: {
    _id: string;
    name: string;
    slug: string;
    authorId:string;
    img: string;
    createdAt?: string;
    updatedAt?: string;
    __v?: number;
  }
}

【讨论】:

  • 知道了,谢谢! ..
【解决方案2】:

如果不想修改类型,建议这样做。

function AuthorContainer(author: AuthorProps) { // }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 2021-07-04
    • 1970-01-01
    • 2021-02-24
    • 2016-03-02
    • 2022-01-18
    • 1970-01-01
    • 2017-08-06
    相关资源
    最近更新 更多