ReactJS:如何将多个数组作为 prop 传递给 ChildComponent?

ReactJS: How do I pass multiple arrays as a prop to ChildComponent?

如何通过两个数组映射并将数据作为道具发送到其他组件?我想从 pricegamedet 发送数据作为道具 Wishlist Component.As 我是新手,如果这段代码不好或不干净,建议我,谢谢提前。

这是我将整个数组发送到 Wishlist 组件的愚蠢方式:

          price.map((game1) => {
            let temp = {
              steamAppID: game1.steamAppID,
              storeID: game1.storeID,
              normalPrice: game1.normalPrice,
              salePrice: game1.salePrice,
            };
            console.log("temp sale", temp.salePrice);
            return tempArr1.push(temp) && tempArr2.push(temp.steamAppID));
          })

这是 WishListData 个组件的全部:

import React, { useEffect, useState } from "react";
import Wishlist from "./Wishlist";
import "./Wishlist.css";
import "animate.css";
import axios from "axios";


const WishlistData = () => {
  const [gamedet, setGameDet] = useState([]);
  const [loaded, setLoaded] = useState(false);
  const [stores, setStores] = useState([]);
  const [price, setPrice] = useState([]);
  const [wishlist, setWishlist] = useState([]);

  useEffect(() => {
    setWishlist(
      localStorage.getItem("Wishlist")
        ? JSON.parse(localStorage.getItem("Wishlist"))
        : []
    );
  }, []);

  const RemoveFromWishlist = (id) => {
    let newList = wishlist.filter((game) => game.gameID !== id);
    setWishlist(newList)
    localStorage.setItem("Wishlist", JSON.stringify(newList));
    console.log("id", [wishlist.pop(id)]);
    console.log("newlist", wishlist);
    setGameDet([])
  };
  const DET_URL = `https://api.rawg.io/api/games`;
  useEffect(() => {
    let isCancelled = false;
    const RAWGdet = () => {
      wishlist &&
        wishlist.map(async (game, index) => {
          const res = await axios({
            url: `https://cors-anywhere.herokuapp.com/${DET_URL}/${game.gameID}?key=${process.env.REACT_APP_RAWG_KEY}`,
            headers: {
              "X-Requested-With": "XMLHttpRequest",
            },
            method: "GET",
          });
          if (!isCancelled) {
            setGameDet((gamedet) => gamedet.concat(res.data));
          }
          setLoaded(true);
        });
    };
    RAWGdet();
    return () => {
      isCancelled = true;
    };
  }, [DET_URL, wishlist]);

  useEffect(() => {
    let isCancelled = false;
    const CSPrice = () => {
      wishlist &&
        wishlist.map(async (game, index) => {
          const res = await axios({
            url: `https://cors-anywhere.herokuapp.com/${DET_URL}/${game.slug}/stores?key=${process.env.REACT_APP_RAWG_KEY}`,
            headers: {
              "X-Requested-With": "XMLHttpRequest",
            },
            method: "GET",
          });
          if (!isCancelled) {
            setStores((stores) => stores.concat(res.data));
          }
          setLoaded(true);
        });
    };
    CSPrice();
    return () => {
      isCancelled = true;
    };
  }, [DET_URL, wishlist]);

  let stm = [];

  stores
    .map((steam) => {
      return steam.results;
    })
    .filter((item) => {
      return item.map((id) => {
        return id.store_id === 1 ? stm.push(id.url) : <>{null}</>;
      });
    });
  let idmain = [];
  stm.map((steamid) => {
    return steamid.split("/").map((item) => {
      return idmain.push(item);
    });
  });

  useEffect(() => {
    let isCancelled = false
    wishlist.length !==0 &&
      wishlist.map((game, index) => {
        return (
          <div key={index}>
            {axios
              .get(
                `https://www.cheapshark.com/api/1.0/deals?storeID=1&steamAppID=${game.steamID}`
              )
              .then((res) => {
                if (!isCancelled){
                  setPrice((price) => price.concat(res.data));
                  setLoaded(true)
                }
              })
              .catch((err) => {
                console.log("ERR", err);
              })}
          </div>
        );
      });
      return () => {
        isCancelled = true
      }
  }, [wishlist]);
  let tempArr1 = [];
  let tempArr2 = [];

  if (loaded ) {
    return (
      <div className="animate__animated animate__slideInDown">
        <div className="wishlist_header">
          <h3>Your Wishlist</h3>
        </div>
        {wishlist.length !== 0 ?  (
          price.map((game1) => {
            let temp = {
              steamAppID: game1.steamAppID,
              storeID: game1.storeID,
              normalPrice: game1.normalPrice,
              salePrice: game1.salePrice,
            };
            console.log("temp sale", temp.salePrice);
            return tempArr1.push(temp) && tempArr2.push(temp.steamAppID));
          }) &&
          gamedet.map((game, index) => {
            // console.log("mad2", game.name);
            return (
              <div id="wishlist_ctn" key={index}>
                <Wishlist
                  // key={index}
                  title={game.name}
                  steamRatingCount={game.id}
                  // steamRatingPercent={game[0].steamRatingPercent}
                  // savings={game[0].savings}
                  // normalPrice={}
                  // salePrice={salePrice}
                  steamAppID={tempArr2}
                  data={tempArr1}
                  image={game.background_image}
                  rem={() => RemoveFromWishlist(game.id)}
                />
              </div>
            );
          })
        ) : (
          <div className="wishlist_header">
            <h3>Add Games!!</h3>
          </div>
        )}
      </div>
    );
  } else {
    return (
      <div className="hmm">
        <div className="wishlist_header">
          <h3>Your Wishlist</h3>
        </div>
        <div className="wishlist_header">
          <h3>Loading Games</h3>
        </div>
        );
      </div>
    );
  }
};

export default WishlistData;

我不明白为什么你需要两个额外的数组,因为你正在映射 price 来填充 tempArr1,其中包含其项目的副本,tempArr2,其中包含其 steamAppID 的副本。

我认为您可以将 price 数组作为 data 传递,并将映射版本作为 steamAppID:

{wishlist.length !== 0 ?  
    (gamedet.map((game, index) => {
        <Wishlist
            // key={index}
            title={game.name}
            steamRatingCount={game.id}
            // steamRatingPercent={game[0].steamRatingPercent}
            // savings={game[0].savings}
            // normalPrice={}
            // salePrice={salePrice}
            steamAppID={price.map(item => item.steamAppID)}
            data={price}
            image={game.background_image}
            rem={() => RemoveFromWishlist(game.id)}
        />;
        </div>
        );
    })
) : (
    <div className="wishlist_header">
        <h3>Add Games!!</h3>
    </div>
)}