Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

reactjs - React Hooks TypeError: products.map is not a function

Im new to react. Im getting this error products.map is not a function. I didnt get any errors related to .map function before but today it suddenly appeared. Can somebody pls help me fix this ?

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to add an other protection at line 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,
  })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...