如下所示,當從父組件向子組件傳遞屬性時,在屬性到達之前,我的代碼首先被執行,當試圖對一個陣列進行.map時,回傳錯誤 "無法讀取未定義的屬性(讀取'map')"。為什么會發生這種情況?
正如你在圖片中看到的,首先你得到了未定義的值,這在 .map 中產生了錯誤。
正如你在圖片中看到的,首先你得到了未定義的值,這在.map中產生了錯誤,然后你得到了屬性
。上層組件:
import React, {useEffect, useState}. from "react"。
import ItemDetail from "./itemDetail" ;
import '././App.css';
import { useParams } from "react-router-dom";
//Component Class
const ItemDetailContainer = (/span>) => {
const [producto, productos] = useState([] )。
const { productId } = useParams() 。
useEffect(() => {
fetch('http://localhost:3000/productos/'/span> productId)
.then(res=>res.json()
.then(data=>productos(資料))
}, [productId])。
console.log(producto)。
return (
<div className="container">
<ItemDetail
nombre={producto.nombre}
id={producto.id}。
precio={producto.precio}
category={producto.category}
imagenes={producto.imagenes}。
ancho={producto.ancho}。
alto={producto.alto} />
</div>/span>
)
}
export default ItemDetailContainer;
子組件:
import React from 'react' /span>;
import { Card } from 'react-bootstrap'/span>;
import ItemCount from './itemCount'。
const ItemDetail = ({ nombre, id, precio, category, imagenes, ancho, alto }) => {
console.log(imagenes)。
return (
< div className="row" key={id} id={id}>
< div className="col-md-6" id="productImage">
<div className="carousel-item"/span>>
{imagenes.map((p) => (
< img src={p} className="d-block w-100" alt={nombre} />
))}
</div>)。
</div>/span>
<div className="col-md-6 producto">/span>
<div className="card">/span>
<Card.Body>/span>
<Card.Title>{nombre}</Card.Title>
<Card.Text>{category}</Card.Text>
<Card.Text>${precio}</Card.Text>
<ItemCount />>
</Card.Body>
</div>
</div>/span>
</div>
);
};
export default ItemDetail;
uj5u.com熱心網友回復:
改變你的代碼,只在imagenes是一個陣列時執行。我個人會重新考慮你是如何構造你的初始狀態的。與其說它是一個空陣列,不如說它是一個物件,所有這些屬性都有默認值。
<div className="carousel-item"/span>>
{ Array.isArray(imagenes) & & imagenes. map((p) => (
< img src={p} className="d-block w-100" alt={nombre} />
))}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/331535.html
標籤:
下一篇:腳本中的相對地址不包括身份資訊

