简体   繁体   English

API 响应映射显示无法读取未定义的属性(读取“映射”)

[英]API response mapping shows Cannot read properties of undefined (reading 'map')

When I make API call and store the response in useState, it shows the data while running console.log(), however when this state value is passed as an argument to another component which is supposed to take the data and mapped it to show the result, it gives me an error saying " Cannot read properties of undefined (reading 'map')" Can anyone help me figure out what's wrong with my code?当我调用 API 并将响应存储在 useState 中时,它会在运行 console.log() 时显示数据,但是当此 state 值作为参数传递给另一个组件时,该组件应该获取数据并将其映射以显示结果,它给我一个错误,说“无法读取未定义的属性(读取‘地图’)”谁能帮我弄清楚我的代码有什么问题?

在此处输入图像描述

Edit - As Mr.Silva suggested below, I added {menFootwears && menFootwears.map((menFootwear)=> () )}编辑- 正如 Mr.Silva 在下面建议的那样,我添加了 {menFootwears && menFootwears.map((menFootwear)=> () )}

It no longer shows error anymore, however, it also doesn't show the data even though the data shows as an output in console.log() in Product.jsx whereas it shows undefined in MenShoes.jsx and WomenShoes.jsx它不再显示错误,但是,它也不会显示数据,即使数据在 Product.jsx 的 console.log() 中显示为 output,而在 MenShoes.jsx 和 WomenShoes.jsx 中显示为未定义

在此处输入图像描述

Here's my code for Product.jsx这是我的 Product.jsx 代码

import { useMediaQuery } from '@mui/material';
import { Box } from '@mui/system';
import React from 'react'
import { theme } from '../style/theme';
import MenShoes from './collections/MenShoes';
import WomenShoes from './collections/WomenShoes';
export const Products = () => {

    const matchScreen = useMediaQuery(theme.breakpoints.down('md'))
    const [isLoading, setIsLoading] = React.useState(true);
    const [menFootwears, setMenFootwears] = React.useState([]);
    const [womenFootwears, setWomenFootwears] = React.useState([]);
 

    //Women FootWears
    async function fetchWomenFootwear () {
        setIsLoading(true)
        await fetch('https://dummyjson.com/products/category/womens-shoes')
            .then(response => response.json())
            .then(response => setWomenFootwears(response.products)) 
        setIsLoading(false);     
    }
    //Men Footwears
    async function fetchMenFootwear () {
        setIsLoading(true)
        await fetch('https://dummyjson.com/products/category/mens-shoes')
            .then(response => response.json())
            .then(response => setMenFootwears(response.products))
        setIsLoading(false)
        
    }
  
    React.useEffect(()=> {
        fetchWomenFootwear()
        fetchMenFootwear()
    }, [])

    const handleProductCard = (id) => {
        console.log('hello')
    } 
    
    console.log( womenFootwears, menFootwears)

  return (
    <Box>
       <WomenShoes data={womenFootwears} onclick={handleProductCard} loadingStatus={isLoading}/>
       <MenShoes data={menFootwears} onclick={handleProductCard} loadingStatus={isLoading}/>
    </Box>
  )
}

Both WomenShoes and MenShoes are designed using the same code except for the API response array data. WomenShoes 和 MenShoes 都是使用相同的代码设计的,除了 API 响应数组数据。

MenShoes/WomenShoes.jsx男鞋/女鞋.jsx

import { ShoppingCartSharp } from '@mui/icons-material';
import { Button, Card, CardActionArea, CardContent, CardMedia, Divider, Rating, Skeleton, Typography, useMediaQuery } from '@mui/material';
import { Box } from '@mui/system';
import React from 'react'
import { theme } from '../../style/theme';


export default function MenShoes({menFootwears, handleProductCard, isLoading}) {

    const matchScreen = useMediaQuery(theme.breakpoints.down('md'))
    
    return(
        <Box pt={2} mt={4}>  
            <Divider variant='middle' sx={{
                "&.MuiDivider-root": {
                    "&::before, &::after": {
                        borderTopColor:theme.palette.primary.light,
                        borderTopWidth:'thin',
                        borderTopStyle:'solid'
                    },
                }
            }}>
                <Typography color={theme.palette.primary.main} variant={!matchScreen ? 'h3': 'h5'}>
                    Men Footwears Collections
                </Typography>
            </Divider>
            <Box display='flex' 
            justifyContent='space-evenly' 
            alignItems='center'
            flexWrap='wrap'
            pt={2}
            mt={2}
            px={2}>
                {menFootwears.map((menFootwear)=> (
                <Card key={menFootwear.id}
                        sx={{maxWidth:335,
                        height:'auto',
                        marginTop:'3.5em',
                        flex:!matchScreen ? '0 0 45%' : '0 0 80%' 
                        }}
                        elevation={4}
                        onClick={()=>{handleProductCard(menFootwear.id)}}>
                    <CardActionArea>
                        {isLoading ? 
                        <>
                            <Skeleton variant='rectangular' width='335' height='220' animation='wave'/>
                        </> :
                            <CardMedia component='img'
                                height='220'
                                image={menFootwear.images[0]}/>}
                        <CardContent sx={{
                            textAlign:'center',
                        }}>
                            { isLoading ? 
                            <>
                                <Skeleton variant='h6' animation='wave'/>
                            </> :
                            <Typography gutterBottom variant='h6'
                            fontWeight='bold' 
                            color={theme.palette.primary.main}>
                                {menFootwear.title}
                            </Typography>}

                            {isLoading ? 
                            <>
                                <Skeleton variant='body2' animation='wave'/>
                            </> :
                            <Typography variant='body2' gutterBottom color={theme.palette.primary.dark}>
                                Brand : {menFootwear.brand}
                            </Typography>}

                            { isLoading ? 
                            <>
                                <Skeleton variant='h5' animation='wave'/>
                            </> :
                            <Typography variant='h5' gutterBottom color={theme.palette.primary.main}>
                                $ {menFootwear.price}
                            </Typography>}
                            <Rating
                            size='small'
                            name="rating"
                            value={menFootwear.rating}
                            readOnly/>
                        </CardContent>
                    </CardActionArea>
                        { isLoading ? 
                            <>
                                <Skeleton variant='rectangular' width='335' height='20' animation='wave'/>
                            </> :
                        <Button size='medium' 
                        sx={{all:'unset',
                            textAlign:'center',
                            fontFamily:theme.typography.fontFamily,
                            fontSize:16,
                            width:'100%',
                            padding:'0.7em',
                            margin:0,
                            color:'white',
                            background:`linear-gradient(90deg, ${theme.palette.primary.main},transparent) ${theme.palette.tertiary.main}`,
                            transition:'background 0.5s',
                            '&:hover': {
                                background:theme.palette.secondary.main,
                            }
                            }}>
                            <span  style={{display:'inline-flex', alignItems:'center'}}>
                                    <ShoppingCartSharp size='small'/>&nbsp;&nbsp;Add to Cart 
                            </span> 
                        </Button>}
                </Card>
            ))}
            </Box>
        </Box>
    )
}

Check before using the map if the variable menFootwears is not undefined or if the array is empty.在使用 map 之前检查变量 menFootwears 是否未定义或数组是否为空。

{menFootwears && menFootwears.map(el => () )}

暂无
暂无

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

相关问题 无法使用 REST 响应读取未定义的属性(读取“地图”) - Cannot read properties of undefined (reading 'map') with REST response 无法读取未定义的属性(读取:'map') - Cannot Read properties of undefined (reading: 'map') 无法读取未定义的属性(读取 &gt; &#39;map&#39;) - Cannot read properties of undefined (reading > 'map') ypeError:无法读取未定义的属性(读取“地图”) - ypeError: Cannot read properties of undefined (reading 'map') 映射到 axios 响应的 _id 时未捕获类型错误:无法读取未定义的属性(读取“_id”) - while mapping into _id of axios response Uncaught TypeError: Cannot read properties of undefined (reading '_id') 在表单中选择 - 通过选项映射问题,无法读取未定义的属性(读取“地图”) - Select in form - Problem mapping through options, cannot read properties of undefined (reading 'map') TypeError:无法读取未定义的属性(读取“地图”) - State 返回未定义 - TypeError: Cannot read properties of undefined (reading 'map') - State returns undefined React.map 错误(无法读取未定义的属性(读取“地图”)) - React .map error (Cannot read properties of undefined (reading 'map')) TypeError:无法读取未定义的属性(正在读取“映射”)(JavaScript 数组映射) - TypeError: Cannot read properties of undefined (reading 'map') (JavaScript array map) 我的 map 给了我无法读取未定义的属性(读取“地图”) - My map gives me Cannot read properties of undefined (reading 'map')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM