【问题标题】:React don't render a map function of an Axios callReact 不渲染 Axios 调用的 map 函数
【发布时间】:2021-01-07 20:21:38
【问题描述】:

我正在尝试制作一个购物车表,其中显示图像、产品名称和删除按钮。我从 localStorage 中获取了每个产品的 id,并使用 Axios.get(by id) 调用该 id 的所有数据。

我创建了一个表格来显示产品的价格、图片和名称,但是我的 .map 函数没有在网站中显示信息(即使我可以通过 console.log 看到它)。代码如下:

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;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    通常你可以改变它,使 renderItems 成为一个功能组件。

    function RenderItems() {
      return memory.map...(etc)
    }
    
    ...
    
    <thead><RenderItems /></thead>
    

    但由于这是一个异步函数,因此您需要使用 useEffect。这个 useEffect 获取数据并将其保存到您的组件状态中。然后一旦它存在,它将在稍后呈现。关键是要把提取和渲染分开。

    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;
    

    【讨论】:

    • 我刚试过,我得到这个错误:Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.。我应该以某种方式删除我在 console.log(toy.price) 之后的回报吗?
    • 我刚刚更新了我的评论!我误读了。尝试新版本(可能需要一些调整,因为这是未经测试的)。
    • 另请注意,您必须从文件顶部的 react 中导入 useState 和 useEffect。
    • 谢谢现在它正在工作......但我不太了解你用来解决这个问题的方法,所以我将阅读这个而不是继续。谢谢!
    • 是的,其余的超出了这个问题的范围。 React 的文档解释了 useState 和 useEffect,所以我会去那里看看。乐于助人!
    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 2020-11-16
    • 2021-12-14
    • 2017-11-01
    • 2019-03-30
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多