【问题标题】:React Typescript - Can't pass fetch response to child component [hooks, functionalComponent]React Typescript - 无法将获取响应传递给子组件[钩子,功能组件]
【发布时间】:2021-03-28 13:19:04
【问题描述】:

我一直在尝试将 response 对象从发出 fetch 请求传递给功能组件的子组件。在父组件中执行此操作的简化代码如下:

 <Datatable data={response} />

然后在子组件内部的想法是映射 Fecth API 发出的每个请求的所有 statusCode 和 statusText 条目,并在表中创建一个新行。应该很容易吧?

但是,我无法理解收到的错误消息Type 'RequestProps | undefined' is not assignable to type 'RequestProps[]'. Type 'undefined' is not assignable to type 'RequestProps[]'。对于上下文,我定义了两个 types 一个具有响应类型,然后具有这些类型的数组的类型,如下所示:

type RequestProps = {
  status: number;
  statusText: string;
}

type Props = {
  data: RequestProps[]; 
}

我有一个沙盒环境here 用于测试。

【问题讨论】:

  • 嗨,Dennis,感谢您帮我检查,但 NetworkDiagnostics 组件中的第 33 行 有一个错误,我很难理解。

标签: reactjs typescript react-hooks


【解决方案1】:

您的初始值为RequestProps[] | undefined,要修复它添加特定的初始类型(仅限RequestProps[] 类型):

// response type is `RequestProps[] | undefined`
  const [response, setResponse] = useState<RequestProps[]>();

// Add an initial value (an empty array `[]`)
  const [response, setResponse] = useState<RequestProps[]>([]);

【讨论】:

  • 有趣!我认为定义状态的类型就足够了......显然不是!感谢您的帮助,我接受了您的回答!
猜你喜欢
  • 2019-10-31
  • 2020-05-08
  • 2021-01-26
  • 2020-11-06
  • 1970-01-01
  • 2017-06-18
  • 2020-08-20
  • 1970-01-01
  • 2020-09-17
相关资源
最近更新 更多