简体   繁体   中英

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

How can I map over array to display all elements from that array?

When I try to render single entry it works but when I map an array it doesn't do anything.

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 :

<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.

Here are different ways you can use Array#map :

  1. A named function as callback:
const data = [1,2,3]
data.map(function foo(d) {
  return d*d
})
  1. An anonymous function as callback:
const data = [1,2,3]
data.map(function (d) {
  return d*d
})
  1. An arrow function (using {} ) as callback:
const data = [1,2,3]
data.map((d) => {
  return d*d
})
  1. An arrow function as callback:
const data = [1,2,3]
data.map((d) => (d*d))
  1. An arrow function (without {} or () ) as callback:
const data = [1,2,3]
data.map((d) => d*d)

Check Traditional functions vs Arrow functions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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