繁体   English   中英

映射一个数组给了我一些 arrays 的未定义,因为它们是空的

[英]Mapping an array gives me undefined for some arrays because they're empty

我正在使用 map function 来循环对象,我想访问 object 中名为“文本”的数组的属性。 但是有些 arrays 是空的,因此 text 属性将是未定义的。 因此,计算机给我一个错误。 我收到这个错误

'TypeError:无法读取未定义的属性'文本''

我的方法是使用三元运算符来检查 item.myStocks[0].text 是否存在,然后再对其循环的每个特定 object 执行。 但它不起作用我正在使用反应。

 {this.state.filteredUsers.map((item)=>(
     <Table.Row  >
         <Table.Cell > <p style={{color:'black'}}> {item.myStocks[0].text? item.myStock[0].text : 'array has no texts... '} </p></Table.Cell>
         <Table.Cell> <p>datecreated </p>  </Table.Cell>
     </Table.Row>
     <Table.Row  >
        <Table.Cell > <p style={{color:'black'}}> text</p></Table.Cell>
        <Table.Cell> <p> datecreated</p>  </Table.Cell>
     </Table.Row>

这是映射对象的外观示例。我正在尝试访问“mystocks”的每个对象数组的第一个文本


{dateCreated: "2020-12-02T03:58:44.560Z", myUploads: Array(0), myStocks: Array(3), _id: "5fc727e84297219a0c59b408", email: "sam@yahoo.com", …}
{dateCreated: "2020-12-02T03:58:44.560Z", myUploads: Array(0), myStocks: Array(2), _id: "5fc730104297219a0c59b40d", email: "hip@gmail.com", …}
{dateCreated: "2020-12-02T03:58:44.560Z", myUploads: Array(0), myStocks: Array(0), _id: "5fc730ea4297219a0c59b412", email: "manny@gmail.com", …}

尝试使用可选链接来验证 myStocks[0] 是否存在以及文本字段

item.myStocks[0]?.text ? item.myStock[0].text : 'array has no texts... '

在您的代码中,您无法处理不存在的 object 的文本字段的问题,因此您需要首先验证它是否存在。 没有可选链接,它看起来像

(item.myStocks[0] && item.myStocks[0].text) ? item.myStock[0].text : 'array has no texts... '

为了检查item.myStocks中的数组是否不为空,您可以检查它在三元中的length 如果大于零,则可以访问第一个元素item.myStocks[0]

也许您需要检查item.myStocks[0]是否也具有text属性。 如有必要,将此三元嵌套在第一个三元内。

item.myStocks[0].text? item.myStocks[0].text: 'has no text property'

{this.state.filteredUsers.map((item)=>(


<Table.Row>
      <Table.Cell > <p style={{color:'black'}}> {item.myStocks.length > 0 ? item.myStock[0].text : 'myStocks array is empty...'} </p></Table.Cell>
     <Table.Cell> <p>datecreated </p>  </Table.Cell>
    

     </Table.Row>
     <Table.Row  >
      <Table.Cell > <p style={{color:'black'}}> text</p></Table.Cell>
     <Table.Cell> <p> datecreated</p>  </Table.Cell>
</Table.Row>

我想出了一个解决办法。 语法有点棘手。 我很感激帮助。

{ item.myStocks.length? item.myStocks[0].text : 'no text'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM