我有两个数组,第一个数组Deals
包含交易列表,其中包含dealId
,buyerId
,sellerId
,第二个数组Customer
包含客户列表它有customerId
,name
的地方。我只想将Deal.sellerId
与Customer.customerId
进行比较,并希望显示Customer.name
。
不要将<DealDetail />
与属性sellerName
的组件混淆,对于此组件,我想要客户名称值。
交易数组:
this.state.updatedDeals.map(deal => <DealDetail key={deal.id} dealID={deal.id} sellerName={deal.sellerId} buyerName={deal.buyerId} />)
客户数组:
this.state.updatedCustomers.map(customer => <li key={customer.id} > {customer.name} </li>)>
我真正想要的是什么:
<DealDetail sellerName={deal.sellerId===customer.customerId ? customer.name} : "Unknown" />)
答案 0 :(得分:1)
您可以尝试以下内容。
this.state.updatedDeals.map(
(deal) =>
{
const c = this.state.updatedCustomers.filter(customer=>deal.sellerId===customer.id);
<DealDetail
key={deal.id}
dealID={deal.id}
sellerName={c.length ==1 ? c[0].name:'unknown'}
buyerName={deal.buyerId}
/>
}
)
答案 1 :(得分:1)
let updatedDeals = [
{dealId: 10, buyerId: 1, sellerId: 26},
{dealId: 11, buyerId: 1, sellerId: 26},
{dealId: 12, buyerId: 1, sellerId: 27},
];
let updatedCustomers = [
{customerId: 26, customerName: 'Isaac'},
{customerId: 28, customerName: 'Jane'}
];
let DealDisplay = [];
updatedCustomers.forEach(cust => {
if(updatedDeals.some(deal => deal.sellerId === cust.customerId)){
DealDisplay.push(cust);
}
});
为什么不将逻辑分开以提高可维护性和可读性。您可以将记录作为临时变量提取到单独的数组中。然后使用变量
渲染视图答案 2 :(得分:0)
从firestore获取数据:
updatedCustomers[doc.id] = doc.data();
用以下方法解决了上述问题:
this.state.updatedDeals.map(deal => (<DealDetail key={deal.id}
sellerName={this.state.updatedCustomers[deal.sellerId].name}
buyerName={this.state.updatedCustomers[deal.buyerId].name}
/>))