【问题标题】:Why is an array that is passed correctly via props returning undefined?为什么通过 props 正确传递的数组返回 undefined?
【发布时间】:2021-12-22 14:56:48
【问题描述】:

我正在尝试通过 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 属性返回 undefined。

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

【问题讨论】:

  • 我无法复制。此外,您可能想要修复拼写。 CardDescrition
  • 你从哪里得到错误?

标签: javascript reactjs typeerror


【解决方案1】:

您的代码将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 挂载时,即使您对值进行硬编码,它们似乎也不会在初始渲染时传递。因此,三元检查 props 是否包含 description 数组。

我现在猜为什么会这样:

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

【讨论】:

  • 感谢您的回复!我收到 TypeError: Cannot read properties of undefined (reading 'map')
  • 我做了一个最小的 repo,我注意到你的代码中还有一个错字。 github.com/snake-py/so-help-react-card
  • 哦,我刚刚注意到,我没有推送代码。对不起,现在一切都应该在那里了。
  • 天哪,它确实有效!太感谢了!!你愿意详细说明问题是什么吗?
  • 我添加了一个解释,不确定是否正确。也许有更多经验的人可以绕过并证实我的猜测。
【解决方案2】:

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

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

【讨论】:

  • 嗨,乔尼,感谢您的回复!这显示了一些其他错误:TypeError: Cannot read properties of undefined (reading 'map')
  • 只需添加一个 ?经过描述,所以props?.description?.map((item) =&gt; (&lt;li&gt;{item}&lt;/li&gt;))
  • 我认为如果要计算该值,这将是问题所在。但它是硬编码的。
猜你喜欢
  • 2021-07-31
  • 2020-09-16
  • 1970-01-01
  • 2021-04-21
  • 2021-03-30
  • 2021-12-26
  • 1970-01-01
  • 2021-05-13
  • 2021-10-17
相关资源
最近更新 更多