简体   繁体   中英

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

How to map through two arrays and send data as props to other component? I want to send data from price and gamedet as a prop to Wishlist Component.As I am new to react, suggest me if this code is not good or unclean too, thanks in advance.

This is the dumb way I send whole array to Wishlist component:

          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));
          })

This is all of WishListData component:

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;

I don't understand why you need two extra arrays since you are mapping price to populate tempArr1 , which contain a copy of its items, and tempArr2 , which contains a copy of its steamAppID s.

I think you could just pass the price array as data , and a mapped version as 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>
)}

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