类型错误:无法读取未定义的反应钩子问题的属性'map'



嗨,我在教程中使用react js挂钩,试图通过更新处于usestate的数组来呈现登录页,但我一直收到这个错误TypeError:无法读取未定义的属性"map"。我可能做错了什么?以下是代码:

登录页:

import React, {useEffect, useState} from 'react';
import Axios from 'axios';
import {Icon, Col, Card, Row} from 'antd';
import ImageSlider from '../../utils/ImageSlider';
const {Meta} = Card;
function LandingPage() {
const [Products, setProducts] = useState([]);
const [Skip, setSkip] = useState(0)
const [Limit, setLimit] = useState(8)
const [PostSize, setPostSize] = useState(0)

useEffect(() => {
const variables = {
skip: Skip,
limit: Limit,
}
getProducts(variables)

}, [])

const getProducts = (variables) => {
Axios.post('/api/product/getProducts', variables)
.then(response => {
if (response.data.success) {
setProducts([...Products, response.data.products])
setPostSize(response.data.postSize)

} else {
alert('Failed to fetch product datas')
}
})
}

const onLoadMore = (event) => {
let skip = Skip + Limit;
const variables = {
skip: skip,
limit: Limit,
}
getProducts(variables)
}

const renderCards = Products.map((product, index) => {
return <Col key={index} lg={6} md={8} sm={24}>
<Card
hoverable={true}
cover={<ImageSlider images={product.images} />}
>
<Meta
title={product.title}
description={`$${product.price}`}
/>
</Card>
</Col>
})

这是接收道具的滑块组件:

import React from 'react'
import { Carousel } from 'antd';
function ImageSlider(props) {
return (
<div>
<Carousel autoplay>
{props.images.map((image, index) => (
<div key={index}>
<img
style={{ width: '100%', maxHeight: '150px' }}
src={`http://localhost:5000/${image}`} alt="productImage" />
</div>
))}
</Carousel>
</div>
)
}
export default ImageSlider

还有一点需要指出,当我使用它时,应用程序可以工作:

setProducts(response.data.products)

然而,我希望能够显示以前的状态产品以及新添加的产品,所以当我这样做时,我会得到TypeError:无法读取未定义的react hooks错误的属性"map":

setProducts([...Products, response.data.products])

你试过这个吗?

setProducts([...Products,...response.data.products])

相关内容

  • 没有找到相关文章

最新更新