React TypeScript如何遍历一个对象?

5
这里需要特别针对React进行说明。
我有一个像这样的对象:
interface Profile {
    name: string;
    title: string;
}

const NewPerson: Profile = {
    name: "John Smith",
    title: "Software Engineer"
}

我希望在React组件中返回该对象的键值对,代码如下:

function MyFunc() {
  return (
   <div>
    {
      Object.keys(NewPerson).map((key) => (
        <div>{key}: {NewPerson[key]}</div>
      ))
     }
    </div>
  )
}

然而,我可以访问它们的 key ,但不能访问它们的值。我遇到了这个错误:

TS: 元素隐式具有'any'类型,因为'type'类型的表达式不能用于索引类型'Profile'上。 在类型“Profile”上没有找到参数类型为“string”的索引签名。

我尝试使用 Object.valuesfilter 但无法解决它。


不,我不这么认为。我一直在阅读那里的答案,但在我的情况下分配 keyof typeof 不是一个选项。我只有一个接口和一个对象。 - Viet
3个回答

8
尝试
interface Profile {
    name: string;
    title: string;
    [key: string]: string;
}
const NewPerson: Profile = {
    name: "John Smith",
    title: "Software Engineer"
}
function MyFunc() {
  return (
   <div>
    {
      Object.keys(NewPerson).map((key: keyof Profile) => (
        <div>{key}: {NewPerson[key]}</div>
      ))
     }
    </div>
  )
}

谢谢您的建议,但是我遇到了这个错误:类型为'(key: "title" | "name") => JSX.Element'的参数无法分配给类型'(value: string, index: number, array: string[]) => Element'。 'key'和'value'的类型不兼容。 'type'不能分配给'title'或'name'类型。 - Viet

5
使用Object.entries与forEach循环相结合的方式,会怎么样呢?就像这样:
Object.entries(NewPerson).map(([key, value]) => {
   <div>{key}: {value}</div>
})

谢谢您的建议,但是 forEach 在 React 中不起作用。 - Viet

1

我也遇到了同样的问题,我是这样解决的:

Object.entries(NewPerson).map(([key, value]) => {
 <div>{key}: {value}</div>
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接