【问题标题】:How to remove null values from props.map [duplicate]如何从 props.map 中删除空值 [重复]
【发布时间】:2019-09-05 08:28:31
【问题描述】:

我正在从 props 映射到“lawList”,但该数组包含很多我希望阻止的 nullValues。

{props.map((lawList, index) => (
  <Table.Body key={index}>
    <Table.Row>
      <Table.Cell>{index + 1}</Table.Cell>
      <Table.Cell>{lawList.lawDTO.name}</Table.Cell>
      <Table.Cell>{lawList.text}</Table.Cell>
      <Table.Cell>{lawList.status}</Table.Cell>
      <Table.Cell>
        {new Date(lawList.latestRevisionDate).toISOString().substring(0, 10)}
      </Table.Cell>
      <Table.Cell>placeholder</Table.Cell>
    </Table.Row>
  </Table.Body>
))}

关于如何从“lawList”中删除所有空值的任何建议?

【问题讨论】:

  • 在使用map之前过滤掉所有的空值,像这样:props.filter(el =&gt; el).map(....)
  • @MayankShukla 我的建议是检查显式值。 false,空字符串,0 都是假的。另外,应该是!!
  • 顺便说一句,你不应该像这里一样将道具作为数组传递
  • @Rajesh 对,添加了正确和正确解决方案的参考:)

标签: javascript reactjs


【解决方案1】:

您可以在数组上使用filter(Boolean) 来过滤掉任何虚假元素。

{props.lawList.filter(Boolean).map((lawList, index) => (
  <Table.Body key={index}>
    <Table.Row>
      <Table.Cell>{index + 1}</Table.Cell>
      <Table.Cell>{lawList.lawDTO.name}</Table.Cell>
      <Table.Cell>{lawList.text}</Table.Cell>
      <Table.Cell>{lawList.status}</Table.Cell>
      <Table.Cell>
        {new Date(lawList.latestRevisionDate).toISOString().substring(0, 10)}
      </Table.Cell>
      <Table.Cell>placeholder</Table.Cell>
    </Table.Row>
  </Table.Body>
))}

【讨论】:

  • Stil 给了我这个错误:gyazo.com/29e461ece009a48f6eaec5fefedc2feb
  • 当我添加这个 {lawList.text.replace(/(]+)>)/ig,"")}
  • @ArastoSahbaei 好的。你能创建一个Minimal, Complete, and Verifiable example吗?如果不了解您的数据的结构,很难说出可能出了什么问题。组件props 也是一个对象,因此问题可能是您尝试使用map,具体取决于您的props 变量的定义。
猜你喜欢
  • 2019-12-08
  • 2013-07-25
  • 2012-09-26
  • 2019-09-22
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2015-09-24
相关资源
最近更新 更多