【问题标题】:TypeError: Cannot read property 'map' of undefined react hooks issueTypeError:无法读取未定义反应挂钩问题的属性“地图”
【发布时间】:2020-06-30 10:35:52
【问题描述】:

您好,我在教程中使用 react js 挂钩,尝试通过更新 usestate 中的数组来呈现登录页面,但我不断收到此错误 TypeError: Cannot read property 'map' of undefined。我可能做错了什么? 下面是代码:

登陆页面:

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: Cannot read property 'map' of undefined react hooks 错误:

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

【问题讨论】:

  • 看起来product.images 未定义,你检查了吗?

标签: javascript arrays reactjs react-hooks


【解决方案1】:

你试过了吗?

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

【讨论】:

  • 是的,谢谢,它对我有用。
猜你喜欢
  • 2021-04-12
  • 2019-09-04
  • 1970-01-01
  • 2021-12-02
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
相关资源
最近更新 更多