简体   繁体   English

数组 map function 不起作用(不在 React 中渲染元素)

[英]Array map function is not working (not rendering elements in React)

How can I map over array to display all elements from that array?如何通过阵列map显示该阵列中的所有元素?

When I try to render single entry it works but when I map an array it doesn't do anything.当我尝试渲染单个条目时它可以工作,但是当我 map 一个数组时它什么也不做。

Below Works:下面的作品:

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

Below does not work:以下不起作用:

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

I have another map in the same render over the same array that works :我有另一个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>

The Array#map method creates a new array populated with the results (ie return value ) of calling a provided function (ie callback ) on every element in the calling array. Array#map方法创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的 function(即回调)的结果(即返回值)。

Here are different ways you can use Array#map :以下是您可以使用Array#map的不同方式:

  1. A named function as callback:一个名为 function 作为回调:
const data = [1,2,3]
data.map(function foo(d) {
  return d*d
})
  1. An anonymous function as callback:匿名 function 作为回调:
const data = [1,2,3]
data.map(function (d) {
  return d*d
})
  1. An arrow function (using {} ) as callback:箭头 function (使用{} )作为回调:
const data = [1,2,3]
data.map((d) => {
  return d*d
})
  1. An arrow function as callback:箭头 function 作为回调:
const data = [1,2,3]
data.map((d) => (d*d))
  1. An arrow function (without {} or () ) as callback:箭头 function (没有{}() )作为回调:
const data = [1,2,3]
data.map((d) => d*d)

Check Traditional functions vs Arrow functions .检查传统函数与箭头函数

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

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