简体   繁体   中英

map is not a function even though I have an array

I looked into a lot of posts with similar issues, but I can't seem to find a solution..

This is my main App.js

import React, { useState, useEffect } from "react";
import { weapons } from "./WeaponsList";
import DisplayWeapon from "./components/DisplayWeapon";

const App = () => {
  const [items, setItems] = useState([]);
  useEffect(() => {
    setItems(weapons);
  }, []);

  return (
    <div className="container">
      <DisplayWeapon items={items} />
    </div>
  );
};

export default App;

This is my DisplayWeapon.js where I want my array to be outputted

import React from "react";

const DisplayWeapon = (items) => {
  console.log(items);
  return (
    <div>
      {items.map((item) => (
        <div>{item.name}</div>
      ))}
    </div>
  );
};

export default DisplayWeapon;

And here is my List of items

export const weapons = [
  {
    name: "Sword",
    id: 1,
  },
  {
    name: "Axe",
    id: 2,
  },
  {
    name: "Greatsword",
    id: 3,
  },
  {
    name: "Hammer",
    id: 4,
  },
];

I already created an alternative version in the App.js which works fine, but once I transfer the data to DisplayWeapons.js it tells me that map is not a function when I console.log it inside of DisplayWeapons.js it shows me that I have an array.

I also tried Object.keys(), but it only gives me the name of the array "items"

Here is the alternate version, which works.

import React, { useState, useEffect } from "react";
import { weapons } from "./WeaponsList";
//import DisplayWeapon from "./components/DisplayWeapon";

const App = () => {
  const [items, setItems] = useState([]);
  useEffect(() => {
    setItems(weapons);
  });

  return (
    <div className="container">
      <div>
        {items.map((item) => (
          <h1>
            {item.name} {item.id}
          </h1>
        ))}
      </div>
    </div>
  );
};

export default App;

When props are passed its passed as an object and you have to expand and take a single property that you need

change

const DisplayWeapon = (items) => {

to

const DisplayWeapon = ({items}) => {

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