我试图从自定义响应数据对象中返回[key, value]对,但是当我尝试循环遍历每个key[value]时,它会给我这个错误:
No index signature with a parameter of type 'string' was found on type 'IResponse'
或者 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IResponse'
。这是我的Detail.tsx:interface IResponse {
birth_year: string;
created: string;
edited: string;
eye_color: string;
films: string[];
gender: string;
hair_color: string;
heigth: string;
homeworld: string;
mass: string;
name: string;
skin_color: string;
species: string[];
startships: string[];
url: string;
vehicles: string[];
}
const Detail = () => {
const [person, setPerson] = useState<IResponse>({} as IResponse);
const { id } = useParams();
useEffect(() => {
api.get(`people/${id}`).then((res) => {
if (res.data) setPerson(res.data as IResponse);
});
}, [id]);
function printValues() {
return Object.keys(person).map((key) => (
<li>
{key}:{person[key]}
</li>
));
}
return <ul>{printValues()}</ul>;
};
我的问题是:为什么这段代码:
function objectEntries() {
const a = "name";
const entries = person[a];
console.log(entries);
}
objectEntries();
这个功能正常,但在printValues函数中出现问题了?