reactjs - typescript |无法遍历自定义类型对象

标签 reactjs typescript

我试图从自定义响应数据对象返回一个 [key, value] 对,但是当我尝试遍历每个 key[value] 时,它给了我这个错误:

在类型“IResponse”上找不到参数类型为“string”的索引签名

元素隐式具有“any”类型,因为类型“string”的表达式不能用于索引类型“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 函数中不行?

最佳答案

我在这里看到 2 个不同的问题。首先你必须调用 print values return <ul>{printValues()}</ul> .其次,当 person.data 在获取数据之前的第一个渲染中为空时,您没有处理。

评论后更新:好吧,既然你有这些,修复类型错误的实际方法就是这样

    let key: keyof IResponse['data'];
    for (key in person.data) {

问题是您没有任何字符串类型的键。所以你需要说你正在使用那个对象的键

如果你不喜欢这种语法,你总是可以使用下面的语法

for (let [key, value] in Object.entries(person.data))

关于reactjs - typescript |无法遍历自定义类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62438186/

相关文章:

javascript - 如何在 ReactJS 项目中使用 ffmpeg.js

javascript - 正在接收数据但无法显示

reactjs - 文件上传不适用于按钮单击 Material -UI V1 ReactJs

使用唯一 ID 进行 Javascript 测试

javascript - ReactJS 中是否有一个函数可以在加载类中的任何内容之前等待 Redux Action 完成?

typescript :类型 'number | null' 不可分配给类型 'number'

javascript - 在 Typescript 中处理表行

带有 ControllerAs 和 TypeScript 类的 AngularJs 指令

angular - ionic 2 : Modal doesn't close when clicking on backdrop

typescript - 预中间件中的 Mongoose typescript 不存在