[英]Nested map on same array doubles on each render
I have an array in the state, and based on a sort field, I order the table differently.我在 state 中有一个数组,并且基于排序字段,我对表进行了不同的排序。 I have a list of clients, and some are type 1, and some are type 2. The type 2 clients are a subset of type 1. So First I get all the type 1 clients, and then for each of those, I find all their children and list them:
我有一个客户列表,有些是类型 1,有些是类型 2。类型 2 客户是类型 1 的子集。所以首先我得到所有类型 1 的客户,然后对于每个客户,我找到所有他们的孩子并列出他们:
<tbody>
{this.state.clients
.filter(x => x.clientTypeId === 2)
.sort((a,b) => sortByField(a, b,this.state.sortOrder === 1 ? 'name' : "registrationNumber", 0) )
.map(client => (
<React.Fragment>
<tr style...
and within the table, I re-sort the client list again, to find its children clients, and order and display them.在表中,我再次对客户列表进行重新排序,以找到其子客户,并对它们进行排序和显示。
{this.state.clients
.filter(x => x.parentClientId === client.id)
.sort((a,b) => sortByField(a,b,this.state.sortOrder === 1 ? 'name' : "registrationNumber", 0) )
.map(subClient => (
<tr className="tableRow" onClick={() => { this.handleSelection(subClient.id); }} key={client.id}>
The problem is, each time I change the sort option, the table of sub-clients doubles in size.问题是,每次我更改排序选项时,子客户表的大小都会加倍。 It seems to add the values again.
它似乎再次添加了值。
The whole method:整个方法:
{!this.state.isLoading &&
<tbody>
{this.state.clients
.filter(x => x.clientTypeId === 2)
.sort((a,b) => sortByField(a, b,this.state.sortOrder === 1 ? 'name' : "registrationNumber", 0) )
.map(client => (
<React.Fragment>
<tr style={mainStyle} className="tableRow" onClick={() => { this.handleSelection(client.id); }} key={client.id}>
<td><strong>{client.name}</strong></td>
...
</tr>
{this.state.clients
.filter(x => x.parentClientId === client.id)
.sort((a,b) => sortByField(a,b,this.state.sortOrder === 1 ? 'name' : "registrationNumber", 0) )
.map(subClient => (
<tr className="tableRow" onClick={() => { this.handleSelection(subClient.id); }} key={client.id}>
<td> > {subClient.name}</td>
...
</tr>
))}
</React.Fragment>
))}
</tbody>
}
I'm not sure why the child objects duplicate each time.我不确定为什么子对象每次都重复。 It's as if it's adding the newly mapped version to the table.
就好像它正在将新映射的版本添加到表中。 What am I doing wrong?
我究竟做错了什么?
Found the error.发现错误。
In the TR tags, I used key={client.id}
in both.在 TR 标签中,我都使用了
key={client.id}
。
The 2nd loop should be using subClient.id
.第二个循环应该使用
subClient.id
。
Fixing this, resolved the issue.解决这个问题,解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.