简体   繁体   English

TypeError list.map 不是 function

[英]TypeError list.map is not a function

Hi could someone tell me why I am getting the list.map is not a function error?嗨,有人能告诉我为什么我得到 list.map 不是 function 错误吗? I don't know why it can't list.map不知道为什么不能list.map

我不知道为什么前 2 个 lan 是未定义的

below is my code下面是我的代码

singleProduct单一产品


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));
  }, [id]);
  return (
    <div>
      <SingleProductComponent list={product} />
      {/* <RelatedProducts list={product} /> */}
      <Review />
    </div>
  );
};

export default SingleProduct;

SingleProductComponent单一产品组件

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;

axiosLink axios链接

import axios from "axios";

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

export default axiosLink;

Can you tell me the reason why?你能告诉我为什么吗? I get this error very often and I don't know the fix yet我经常收到此错误,但我还不知道修复方法

this is my api structure这是我的 api 结构

api格式

you need to initialize your product state with an array like below您需要使用如下数组初始化您的产品 state

const [product, setProduct] = useState([])

Check in.network (inspect element ->.network) if your data is correctly coming to you.检查 in.network(检查元素 ->.network)如果你的数据正确地传给你。 Console log your data as well and check if its array.控制台也会记录您的数据并检查它的数组。 Practically this error says that your "list" is not an array, and it cannot map through it.实际上这个错误表明你的“列表”不是一个数组,它不能通过它 map。

Also you should use useEffect(()=>{},[]) so it should fetch your api only once, and initialise your useState for product as empty array [].您还应该使用 useEffect(()=>{},[]),这样它应该只获取您的 api 一次,并将产品的 useState 初始化为空数组 []。

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

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