【问题标题】:map is not function in object [closed]地图在对象中不起作用[关闭]
【发布时间】:2021-10-27 08:20:58
【问题描述】:

我试图链接传递对象,它说地图不是函数。我一路尝试,但没有运气。知道我犯了什么错误。

输入

const sample = [
  {
    path: "/website",
    par: {
      abc: "234",
      def: "567",
      ghi: "8910"
    }
  }
];


{sample.length !== 0 ? (
        sample.map((sample) => (
          <Menu.Item
        
          >
            <Link
              to={{
                pathname: sample.path,
                search: createURL(sample)
              }}
            >
              {"Sample"}{" "}
            </Link>
          </Menu.Item>

Map is not a function error

【问题讨论】:

  • 真的是数组还是字符串? console.log(Array.isArray(sample)) 输出什么?是否需要将字符串解析为JSON.parse?的数组
  • 尝试将对象名称更改为其他名称,而不是与地图函数 sample.map((here) => {}) 中的数组名称相同

标签: javascript reactjs react-router


【解决方案1】:

你也可以这样做。您可以使用Optional chaining?

检查您的数据数组

更多关于Optional chaining?

另外,您需要验证您的数据是否为数组格式。您可以使用Array.isArray(sample) 进行检查。

import React from "react";

const samples = [
  {
    path: "/website",
    par: {
      abc: "234",
      def: "567",
      ghi: "8910"
    }
  }
];

const App = () => {
  
  return (
   <React.Fragment>
    {Array.isArray(samples) && samples?.map(sample => {
      return (
        <div>
          {JSON.stringify(sample)}
        </div>
      )
    })}
  </React.Fragment>
  );
};

export default App;

【讨论】:

    【解决方案2】:

    试试这个

    {sample && sample.length && (
            <>
              {sample.map((item, index) => (
                <Menu.Item
                  key={index}
                  className={"text"}
                >
                  <Link
                    to={{
                      pathname: item.path,
                      search: createURL(item),
                    }}
                  >
                    {"item"}{" "}
                  </Link>
                </Menu.Item>
              ))}
            </>
          )}
              
    

    【讨论】:

    • 如果sample 是一个已定义的空数组,那么.map 肯定能够处理它。此代码可能会无意中输出其他值,例如 0 如果它是一个空数组。
    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 2012-08-06
    • 2015-05-13
    相关资源
    最近更新 更多