【问题标题】:Argument of type 'Response' is not assignable to parameter of type 'SetStateAction`“响应”类型的参数不可分配给“SetStateAction”类型的参数
【发布时间】:2021-03-08 11:25:04
【问题描述】:

这是我的 CommentResponse 接口,它是来自 API 响应的数组内部对象的结构

interface CommentResponse {
  body: string;
  email: string;
  id: number;
  name: string;
  postId: number;
}

使用 setAllComments (useState-hook) 从 API 响应中设置数据时,出现以下错误

/typescript-demo/src/components/Dashboard/index.tsx
TypeScript error in /typescript-demo/src/components/Dashboard/index.tsx(35,20):
Argument of type 'Response' is not assignable to parameter of type 'SetStateAction<CommentResponse[]>'.
  Type 'Response' is missing the following properties from type 'CommentResponse[]': length, pop, push, concat, and 28 more.  TS2345
    32 |     comments = await comments.json();
    33 |     console.log(comments);
    34 |     // comments = await JSON.parse(comments);
  > 35 |     setAllComments(comments);
       |                    ^
    36 |   };
    37 | 
    38 |   useEffect(() => {

@RajaJaganathan

const [allComments, setAllComments] = useState<CommentResponse[]>([]);

  const commentService = async () => {
    const COMMENTS_API = `https://jsonplaceholder.typicode.com/comments`;    
    let comments = await fetch<Array<CommentResponse>>(COMMENTS_API);

    comments = await comments.json();
    console.log(comments);

    setAllComments(comments);
  };

我访问了其他 StackOverflow 和 Google 链接,但找不到解决方案

【问题讨论】:

  • 你也可以显示你的useState代码吗?
  • @RajaJaganathan ,我已经在上面编辑过,请检查!

标签: reactjs typescript


【解决方案1】:

听起来comments 是一个响应对象。要从中提取值,您需要对其调用 .json()

看起来.json 中的泛型已被删除,因此您必须使用类型断言:

fetch('some-api')
  .then(res => res.json())
  .then(comments => setAllComments(comments as Array<CommentResponse>))
  .catch(handleErrors);

【讨论】:

  • 谢谢,但我现在收到此错误 - ``` 预期的类型参数为 0,但得到了 1。TS2558 30 |让 cmets = await fetch(COMMENTS_API); 31 | > 32 | cmets = 等待 cmets.json>(); | ^ 33 |控制台.log(cmets); 34 | // cmets = 等待 JSON.parse(cmets); 35 | // setAllComments(cmets); ```
  • 您能告诉我如何使用 async/await 将 Promise 对象转换为数组吗? cmets = 等待 cmets.json>();这引发了这个错误 - 预期的类型参数为 0,但得到了 1。
  • 这是抛出错误,因为 CommentResponse 接口不需要任何参数
  • 我认为this 是理所当然的,看起来我在某处做错了什么,一秒钟......
  • 将“Response”类型转换为“CommentResponse[]”类型可能是一个错误,因为这两种类型都没有充分重叠。如果这是故意的,请先将表达式转换为“未知”。这就是我现在得到的:(
【解决方案2】:

在您的情况下,来自 fetch 的响应是返回一个 Object 类型的对象 其值为 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/comments", redirected: false, status: 200…}

让你的界面在正确的位置:

const COMMENTS_API = `https://jsonplaceholder.typicode.com/comments`;    
let comments =  await fetch(COMMENTS_API);

let result: Array<CommentResponse> = await comments.json();

setAllComments(result);

您可以同时使用result:Array&lt;CommentResponse&gt;result:CommentResponse[]

检查 fetch 和 axios 的代码 demo here

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2021-01-03
    • 2021-07-14
    • 2021-05-16
    • 2021-12-04
    相关资源
    最近更新 更多