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

Why is an array that is passed correctly via props returning undefined?

我正在尝试通过 props 传递此数组来加载 <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

我得到

TypeError: Cannot read properties of undefined (reading '0')

我不确定为什么 props.description prop 返回未定义。

此外,这个 TypeError 似乎只发生在 props.description 属性上。

您的代码拼写错误 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 组件,代码应该可以在没有初始检查的情况下工作。

好吧,这可能是因为在安装三个 description 属性的过程中可能未定义,你可以通过这样做来避免这个错误 props?.description[0],如果你想渲染数组中的所有值您可以执行此操作的 CardDescrition 组件

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