为什么通过props正确传递的数组返回undefined?

3
我试图通过将数组传递给组件属性来加载字符串数组中的每个字符串到一个 <li> 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.description属性返回undefined。

另外,这个TypeError似乎只在使用props.description属性时发生。


1
我无法复现。另外,您可能需要修正拼写错误。CardDescrition - CertainPerformance
你在哪里出现了错误? - Michael
2个回答

1

您的代码将CardDescrition错误拼写为CardDescription

尝试:

{props.description ? <CardDescription description={props.description} /> : ''}

并在描述中:

function CardDescription(props) {
    return (
        <div>
            <ul>
                {props.description.map(des => <li>des</li>)}
            </ul>
        </div>
    )
}

please find the minimal repo I created:

https://github.com/snake-py/so-help-react-card

解释:

我尝试从我的理解中解释发生了什么。

当Carditems挂载时,即使您硬编码了值,它们似乎在初始渲染时也没有传递。因此,进行三元检查,如果props包括description数组,则进行检查。

我现在猜测为什么会这样:

可能是因为它们在包装组件内部。如果删除组件,则代码应该可以在没有初始检查的情况下工作。


谢谢回复!我得到了 TypeError: Cannot read properties of undefined (reading 'map')。 - Kauan Abrahão
我制作了一个最小化的代码仓库,我注意到你的代码中也有一个拼写错误。https://github.com/snake-py/so-help-react-card - Snake_py
哦,我刚刚注意到我没有推送代码。抱歉,现在应该一切都在那里了。 - Snake_py
哇,它真的可以工作了!非常感谢!您能详细说明一下问题是什么吗? - Kauan Abrahão
我添加了一些解释,不确定是否正确。也许有更多经验的人可以过来确认我的猜测。 - Snake_py
非常感谢您的帮助,我真的很感激。 - Kauan Abrahão

1

很可能是由于在挂载三个描述时,描述属性可能未定义,您可以通过执行此操作避免此错误props?.description[0],另外,如果您想在CardDescription组件中呈现数组中的所有值,则可以执行此操作

   props?.description.map((item) => (<li>{item}</li>))

嘿,约翰尼,感谢您的回复!这显示了另一个错误:TypeError: 无法读取未定义的属性(读取 'map') - Kauan Abrahão
只需在描述后添加一个问号,这样 props?.description?.map((item) => (<li>{item}</li>)) - Mark Williams
我认为如果该值被计算,这将是问题所在。但它是硬编码的。 - Snake_py

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接