我正在嘗試<li>通過 props 傳遞這個陣列來加載html 標簽中字串陣列的每個字串:
<CardItem
src='https://static.news...koinex-banner.png'
text='my text'
label='Adventure'
path='/products'
description={["someText1", "someText2", "someText3", "someText4"]}
/>
function CardItem(props) {
return (
<>
<li className='cards__item'>
<Link className='cards__item__link' to={props.path}>
<figure className='cards__item__pic-wrap' data-category={props.label}>
<img
className='cards__item__img'
alt='Travel Image'
src={props.src}
/>
</figure>
<div className='cards__item__info'>
<h5 className='cards__item__text'>{props.text}</h5>
</div>
<CardDescription description={props.description} />
</Link>
</li>
</>
);
}
export default CardItem;
function CardDescription(props) {
return (
<div>
<ul>
<li>{props.description[0]} </li>
</ul>
</div>
)
}
export default CardDescription
我得到
型別錯誤:無法讀取未定義的屬性(讀取“0”)
我不確定為什么props.descriptionprop 回傳 undefined 。
此外,這個 TypeError 似乎只發生在props.description道具上。
uj5u.com熱心網友回復:
好吧,這可能是因為在安裝三個描述道具期間可能未定義,您可以通過執行此操作來避免此錯誤props?.description[0],此外,如果您想在 CardDescrition 組件內呈現陣列中的所有值,您可以執行此操作
props?.description.map((item) => (<li>{item}</li>))
uj5u.com熱心網友回復:
您的代碼拼錯CardDescrition 為CardDescription
嘗試:
{props.description ? <CardDescription description={props.description} /> : ''}
并在描述中:
function CardDescription(props) {
return (
<div>
<ul>
{props.description.map(des => <li>des</li>)}
</ul>
</div>
)
}
請找到我創建的最小回購:
https://github.com/snake-py/so-help-react-card
解釋:
我試圖從我所理解的那里解釋那里發生的事情。
當 Carditems 掛載時,即使您對這些值進行了硬編碼,它們似乎也不會在初始渲染時傳遞。因此,三元檢查道具是否包含description陣列。
我現在猜測這是為什么:
也許是因為它們位于Link. 如果您洗掉Link組件,代碼應該可以在沒有初始檢查的情況下作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354878.html
標籤:javascript 反应 类型错误
上一篇:在什么情況下移除CSS過渡?
