【问题标题】:TypeError list.map is not a functionTypeError list.map 不是函数
【发布时间】:2023-01-20 19:23:59
【问题描述】:

嗨,有人能告诉我为什么我得到 list.map is not a function 错误吗?

下面是我的代码

单一产品


import axiosLink from "../instance/axiosLink";

const SingleProduct = () => {
  const { _id } = useParams();
  const [product, setProduct] = useState({});
  useEffect(() => {
    axiosLink
      .get(`/api/products${_id}`)
      .then(({ data }) => {
        setProduct(data);
      })
      .catch((error) => console.log(error));
  });
  return (
    <div>
      <SingleProductComponent list={product} />
      {/* <RelatedProducts list={product} /> */}
      <Review />
    </div>
  );
};

export default SingleProduct;

单一产品组件

import React from "react";

const SingleProductComponent = ({ list }) => {
  return (
    <div>
      {list &&
        list.map((item, index) => {
          return (
            <div key={index}>
              <div className="SingleProduct">
               .........
                </div>
              </div>
            </div>
          );
        })}
    </div>
  );
};

export default SingleProductComponent;

axios链接

import axios from "axios";

const axiosLink = axios.create({
  baseURL: "http://localhost:8000/",
  responseType: "json",
});

export default axiosLink;

你能告诉我为什么吗?我经常收到此错误,但我还不知道修复方法

这是我的 api 结构

【问题讨论】:

  • product 不是数组
  • 您正在将 product 初始化为一个对象,然后执行 list.map。也许您的 XHR 正在返回一个数组,但对于第一次加载,产品是一个对象。所以你需要确保你的默认值是正确的

标签: reactjs


【解决方案1】:

你可以试试

const SingleProduct = () => {
  const { _id } = useParams();
  const [product, setProduct] = useState();
  useEffect(() => {
    axiosLink
      .get(`/api/products${_id}`)
      .then(({ data }) => {
        setProduct(data);
      })
      .catch((error) => console.log(error));
  }, []);

【讨论】:

    【解决方案2】:

    检查网络(检查元素 -> 网络)如果你的数据正确地传给你。控制台也会记录您的数据并检查它的数组。实际上,此错误表明您的“列表”不是数组,并且无法通过它进行映射。

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 1970-01-01
      • 2020-06-29
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2021-06-05
      • 2019-10-03
      相关资源
      最近更新 更多