【发布时间】: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