【问题标题】:ReactJS: How do I pass multiple arrays as a prop to ChildComponent?ReactJS:如何将多个数组作为道具传递给子组件?
【发布时间】:2021-12-08 07:24:34
【问题描述】:

如何映射两个数组并将数据作为道具发送到其他组件?我想将来自pricegamedet 的数据作为道具发送到Wishlist Component。由于我是新来的反应,如果此代码也不好或不干净,请建议我,提前致谢。

这是我将整个数组发送到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;

【问题讨论】:

    标签: javascript arrays reactjs react-props


    【解决方案1】:

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

    我认为您可以将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>
    )}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2019-07-03
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多