繁体   English   中英

如何在React中修复“ TypeError:category.map不是函数”错误

[英]How to fix “TypeError: categories.map is not a function” error in React

我不断收到此错误,表明categories.map不是函数,但我不明白为什么。 我正在为从API调用接收的数据设置类别,但一直收到此错误。 另外,有没有一种方法可以轻松地调用父对象的子对象? API数据嵌套大约4-5层深度,并且它们都有不同的名称,那么我将如何遍历所有这些数据呢?

控制台中的response.data外观示例(打开了一些嵌套对象)

在此处输入图片说明

这是我的组件:

class Menu extends React.Component {
  state = {
    categories: []
  };

  componentDidMount() {
    axios
      .get("https://www.ifixit.com/api/2.0/categories")
      .then(response => this.setState({ categories: response.data }));
  } 

  render() {
    let categories = this.state.categories;
    return (
      <div>
        <ul>
          {categories.map((m, index) => {
            return (
              <li key={index}>
                {m.children && <Menu categories={m.children} />}
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default Menu;

编辑:当我使用Object.keys它给我错误“未捕获的不变违规:对象作为React子无效(找到:具有键的对象...)”,然后列出了我正在调用的对象内的所有键。 有谁知道我如何调用该函数(可能是递归的?)以将此函数应用于对象中的所有对象?

这是我更新的代码:

class Menu extends React.Component {
  state = {
    collapsed: false,
    categories: []
  };

  componentDidMount() {
    axios
      .get("https://www.ifixit.com/api/2.0/categories")
      .then(response => this.setState({ categories: response.data}));
  } 

  render() {
    const { categories } = this.state;
    return (
      <div>
        {Object.keys(categories).map((item, i) => (
          <li key={i}>
            <span>{categories[item]}</span>
          </li>
        ))}
      </div>
    );
  }
}

export default Menu;

您可以将属性对象映射到数组并进行处理。

let result = Object.entries(data).map(( [k, v] ) => ({ [k]: v }));

改成

componentDidMount() {
    axios
      .get("https://www.ifixit.com/api/2.0/categories")
      .then(response => this.setState({ 
       categories: Object.entries(response.data).map(( [k, v] ) => ({ [k]: v }) }));
  } 

问题是response.data不是array而是一个json对象。

您可以使用以下代码基于键进行映射:

Object.keys(categories).map((key, index) => {
  console.log(categories[key]);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM