简体   繁体   English

React 不呈现 Axios 调用的 map function

[英]React don't render a map function of an Axios call

I'm trying to make a shopping cart table in which it shows an image, name of the product and a remove button.我正在尝试制作一个购物车表,其中显示图像、产品名称和删除按钮。 I've the id of each product from the localStorage and call all the data of that id with Axios.get(by id).我从 localStorage 中获取了每个产品的 ID,并使用 Axios.get(by id) 调用该 ID 的所有数据。

I'd created a table to show the price, image and name of the product, but my.map function don't show the info in the website (even though I can see it with a console.log).我创建了一个表格来显示产品的价格、图像和名称,但是 my.map function 没有在网站上显示信息(即使我可以通过 console.log 看到它)。 Here is the code:这是代码:

import Axios from "axios";
import React from "react";

function ClientCardBlock() {
  let memory = window.JSON.parse(localStorage.getItem("toy"));
  console.log(memory); **this log shows me that all the IDs are now in an array**

  const renderItems = () => {
    memory.map(
      async (toy_id) =>
        await Axios.get(`http://************/${toy_id}`).then(
          (response) => {
            const toy = response.data;
            console.log(toy.price); **this log show me the price of each toy, so it's working**
            return (
              <tr key={toy._id}>
                <th>
                  <img
                    alt=""
                    className="card-img-top embed-responsive-item"
                    src={`http://*********/${toy.images}`}
                  />
                </th>
                <th>$ {toy.price}</th>
                <th>
                  <button>Remove</button>
                </th>
              </tr>
            );
          }
        )
    );
  };

  return (
    <div>
      <table className="table table-bordered">
        <thead>
          <tr>
            <th scope="col">Image product</th>
            <th scope="col">Product</th>
            <th scope="col">Remove</th>
          </tr>
        </thead>
        <thead>{renderItems()}</thead>
      </table>
    </div>
  );
}

export default ClientCardBlock;

https://imgur.com/a/bthMJN4

Normally you'd be able to just change it so that renderItems is a functional component.通常你可以只改变它,使 renderItems 成为一个功能组件。

function RenderItems() {
  return memory.map...(etc)
}

...

<thead><RenderItems /></thead>

but since this is an async function, you need to use a useEffect.但由于这是一个异步 function,因此您需要使用 useEffect。 This useEffect gets the data and saves it into your component state. Then once it exists, it will render later.这个useEffect获取数据,保存到你的组件state里面,然后一旦存在,后面再渲染。 The key point is to seperate the fetching from the rendering.关键点是将提取与渲染分开。

function ClientCardBlock() {
  const [data, setData] = useState([]);

  useEffect(() => {
    /* this runs on component mount */
    const memory = window.JSON.parse(localStorage.getItem("toy"));

    Promise.all(memory.map((toy_id) => Axios
                .get(`http://************/${toy_id}`)
                .then((response) => response.data)))
                /* Wait on the Promise.All */
                .then(newData => {
                  /* Set the data locally */
                  setData(newData);
                });
  }, []);

  return (
    <div>
      <table className="table table-bordered">
        <thead>
          <tr>
            <th scope="col">Image product</th>
            <th scope="col">Product</th>
            <th scope="col">Remove</th>
          </tr>
        </thead>
        <thead>
          {data.map(toy => (
              <tr key={toy._id}>
                <th>
                  <img
                    alt=""
                    className="card-img-top embed-responsive-item"
                    src={`http://*********/${toy.images}`}
                  />
                </th>
                <th>$ {toy.price}</th>
                <th>
                  <button>Remove</button>
                </th>
              </tr>
           )}
        </thead>
      </table>
    </div>
  );
}

export default ClientCardBlock;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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