React TypeScript中如何正确获取UserData对象type的id字段
解决React TypeScript中无法获取API返回数据type.id的问题
问题原因
你当前的UserData接口里把type定义成了any[](数组类型),但实际API返回的type是单个对象(包含id和name字段),所以调用i.type.id时,数组没有id属性,导致无法获取。
修正步骤
定义Type的具体类型
先为API返回的type对象单独定义接口,明确它的结构:interface QuestionType { id: number; name: string; }修正UserData接口
将原来的type: any[]替换为type: QuestionType,同时修正那些API可能返回null的字段类型(避免类型不匹配报错):interface UserData { id: number; question: string; updated_at: string; deleted_at: string | null; // API返回可能为null old_question_id: string | null; // API返回可能为null horizontal: number; type_id: number; solving_explanation: string; user_id: string; difficulty_level: string; explanation_image_id: string | null; // API返回可能为null type: QuestionType; // 替换为对象类型 // 如果需要用到API返回的其他字段(如options、collections),可以补充对应的类型定义 }正确获取type.id
修正类型后,就可以正常访问type.id了。如果担心type可能为undefined或null,可以用可选链操作符?.做安全访问:{question.map((item) => { console.log(item.type?.id); // 可选链避免空值报错 return null; // React组件中map需返回JSX元素,仅打印可返回null })}
内容的提问来源于stack exchange,提问作者Jayprakash Singh
相关产品推荐
相关产品推荐

