这是我的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链接,但无法找到解决方案
在您的情况下,来自fetch的响应将返回Object
类型为value的对象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);
您可以同时使用typeresult:Array<CommentResponse>
或result:CommentResponse[]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句