【问题标题】:React Hooks TypeError: products.map is not a functionReact Hooks TypeError:products.map 不是函数
【发布时间】:2021-04-07 09:44:14
【问题描述】:

我是新手。我收到此错误 products.map 不是函数。我之前没有收到任何与 .map 函数相关的错误,但今天它突然出现了。有人可以帮我解决这个问题吗?

import SingleProduct from "./SingleProduct";
import axios from "axios";
import { Container, Grid, Grow } from "@material-ui/core";

const Products = () => {
  const [products, setProducts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const classes = useStyles();

  const getData = () => {
    axios
      .get("http://localhost:4000/api/products")
      .then((res) => {
        setProducts(res.data);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  React.useEffect(getData, []);
  return (
    <div>
        <Container>
          <Grow in>
            <Grid container spacing={6}>
              {products.map((product, index) => (
                <SingleProduct key={index} product={product} />
              ))}
            </Grid>
          </Grow>
        </Container>
    </div>
  );
};

export default Products;

【问题讨论】:

  • 发生这种情况是因为 products 不是数组。由于您的初始状态是一个数组,因此您的 res.data 没有返回一个数组,很可能它是一个对象。您需要检查 res.data 返回的内容
  • 您可以在调用 setProducts 之前登录res 吗?也请登录products。该错误意味着您将其设置为不是数组的东西。
  • console.log(res) 给了我这个 {data: " config: {url: "localhost:4000/api/products", method : "get", headers: {…}, baseURL: "localhost:4000/api", transformRequest: Array(1), …}。类似的东西
  • console.log(products) 给我这个 。类似的东西
  • res.data 似乎返回的是 HTML 文档而不是 JSON。获取时后端是否存在问题,例如某种错误?

标签: reactjs axios array.prototype.map


【解决方案1】:

尝试在第 43 行添加其他保护 => https://github.com/muneebghani/semproject/blob/master/client/src/components/products/Products.js

) : products && (products.length === 0) ? (
  toast.error("Error: There are no products in DB", {
    position: toast.POSITION.TOP_CENTER,
    toastId: "",
    transition: Slide,
  })

【讨论】:

  • 稍后会做,这不会导致任何错误,所以请尝试为我的问题提供解决方案。
【解决方案2】:

在你的then中,你应该首先验证res.data是一个数组。

if(Array.isArray(res.data)) { 
    setProducts(res.data) 
} else { 
    throw new Error (“data invalid”)
}

实际的解决方案似乎是通过您的回复解决问题。无论如何,最好验证您在前端得到了正确的响应。

【讨论】:

猜你喜欢
  • 2019-04-16
  • 2020-01-27
  • 1970-01-01
  • 2019-11-29
  • 2019-04-01
  • 1970-01-01
  • 2021-08-31
  • 2020-07-22
  • 2020-11-30
相关资源
最近更新 更多