【问题标题】:Array map function is not working (not rendering elements in React)数组映射功能不起作用(不在 React 中渲染元素)
【发布时间】:2021-03-07 17:50:26
【问题描述】:

我如何通过数组map 显示该数组中的所有元素?

当我尝试渲染单个条目时它可以工作,但是当我映射一个数组时它什么也不做。

以下作品:

<h1>{thisSeries[0].productColor}</h1>;

以下不起作用:

{thisSeries.map((el) => {
  <h1>PRODUCT: {el.productColor}</h1>;
})}

我有另一个map 在同一个数组的同一渲染中有效

<div>
  {thisSeries.length >= 0 &&
    thisSeries.map((el) => (
      <Link
        key={el._id}
        className="link"
        to={`/pr/add/ph/m/p/variant/${el._id}`}
      >
        <button
          style={{ width: "80%" }}
          onClick="window.location.reload();"
        >
          {el.title}
        </button>
      </Link>
    ))}
</div>

【问题讨论】:

  • 成功了,谢谢!如果有箭头,为什么会这样?

标签: javascript arrays reactjs arrow-functions


【解决方案1】:

Array#map 方法创建一个新数组,其中填充了在调用中的每个元素上调用提供的函数(即 回调)的结果(即 返回值)数组。

您可以通过以下不同方式使用Array#map

  1. 作为回调的命名函数:
const data = [1,2,3]
data.map(function foo(d) {
  return d*d
})
  1. 作为回调的匿名函数:
const data = [1,2,3]
data.map(function (d) {
  return d*d
})
  1. 一个箭头函数(使用{})作为回调:
const data = [1,2,3]
data.map((d) => {
  return d*d
})
  1. 作为回调的箭头函数:
const data = [1,2,3]
data.map((d) => (d*d))
  1. 一个箭头函数(没有{}())作为回调:
const data = [1,2,3]
data.map((d) => d*d)

检查Traditional functions vs Arrow functions

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多