【问题标题】:I am getting a red squiggle under my map function but my code is still compiling, why is this and how can I fix it?我的 map 函数下出现红色波浪线,但我的代码仍在编译,为什么会这样,我该如何解决?
【发布时间】:2021-05-18 17:37:39
【问题描述】:

这是我正在迭代的数组:

[
        {
            "Categories": [
              {
                "Name": "Program",
                "Description": "This is a program",
                "Errors": [
                  {
                    "Name": "Program_not_found",
                    "Value": 1,
                    "Description": "There is an error in this program."
                  }
                ]
              },
              {
                "Name": "ProgramTwo",
                "Description": "This is programTwo.",
                "Errors": [
                  {
                    "Name": "ProgramTwo is not found",
                    "Value": 1
                  },
                  {
                    "Name": "ProgramTwo is missing data",
                    "Value": 2
                  }
                ]
              }
            ]  
          }
    ]  

在另一个文件中,我正在遍历这些数据并在此处的地图下得到一个红色曲线:

{Errors.map(({Name, Value, Description}, key)

我的代码编译并正确显示了信息。如果代码正在编译,我不明白为什么 map 函数下面有一个红色的波浪线。当我将鼠标悬停在 .map 上时,它不会提供有关错误的任何信息。我希望有人能告诉我为什么会发生这种情况以及如何解决它。这是我的组件的样子:

const Categories = () => {
return (
<h1>Error Codes</h1>
<div className="error-codes">
        {errorCodes.map(({Categories}, key) => (
          <div key={key}>
            {Categories.map(({Name, Description, Errors}, key) => (
              <div key={key}>
                <p>{Name}</p>
                <p>{Description}</p>
                {Errors.map(({Name, Value, Description}, key) => ( //Getting red squiggle under map here
                  <div key={key}>
                    <p>{Name}</p>
                    <p>{Value}</p>
                    <p>{Description}</p>
                  </div>
                ))}
              </div>
            ))}
          </div>
        ))}
      </div>
)
}
export default Categories;

【问题讨论】:

  • 也许 Errors 可能为 null 或未定义(例如在初始化时),然后它将没有属性 map。

标签: arrays json reactjs array.prototype.map


【解决方案1】:

我猜这个问题与打字稿有关。我可以通过这样做使错误消失:{(Errors as any []).map.我在这里找到了这个解决方案:typescript, Array.prototype.map() has error 'expression is not callable' when the callee array is union with empty array

【讨论】:

    【解决方案2】:
    1. 只是猜测,但它可能是你的 linter,这个 linter 想告诉你你的行太长了。

    2. 另一个猜测是您没有将Errors 初始化为数组类型。由于没有声明类型,你 linter 想告诉你这可能不起作用,因为 Errors 你有任何类型。

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多