react-table-v6行内多键值对映射及accessor返回undefined问题解决
问题背景
给定数据数组(注:原数据tags写法存在语法错误,已修正为数组格式):
my_tags = [ { item: 1, tags: [ {name: 'LandingPage', value: 'true'}, {name: 'Country', value: 'GB'}, {name: 'Carrier', value: 'Evri'}, {name: 'EventCode', value: 'Dispatched'}, ] }, { item: 2, tags: [ {name: 'LandingPage', value: 'true'}, {name: 'Country', value: 'USA'}, {name: 'Carrier', value: 'RoyalMail'}, {name: 'EventCode', value: 'Dispatched'}, ] } ]
使用react-table-v6时,希望表格每行展示tags中Country和Carrier的value值,但原accessor配置返回[undefined, undefined]:
{ Header: 'Alert tags', id: 'tags', accessor: (data) => { const res = data.tags.map(items => items.tags?.find(i => i?.name === 'Carrier').value); console.log('res:', res); }, }
但单独测试逻辑能得到正确结果,且accessor: item => (item.tags.map(i => i.name))可正常获取所有name值。
错误原因
原accessor存在多余嵌套:data是表格每行对应的单条数据,data.tags已经是当前行的标签数组,无需再调用map遍历data.tags并访问items.tags——该属性不存在,因此返回undefined。
正确实现方案
方案1:单独展示Carrier的值
{ Header: 'Carrier', id: 'carrier', accessor: (data) => { const carrierTag = data.tags.find(tag => tag.name === 'Carrier'); return carrierTag ? carrierTag.value : 'N/A'; // 增加默认值避免找不到标签时报错 } }
方案2:同时展示Country和Carrier的值
{ Header: 'Alert tags', id: 'tags', accessor: (data) => { const country = data.tags.find(tag => tag.name === 'Country')?.value || 'N/A'; const carrier = data.tags.find(tag => tag.name === 'Carrier')?.value || 'N/A'; return `${country} | ${carrier}`; // 用分隔符拼接两个字段值 } }
验证结果
使用上述配置后,表格每行将正确显示对应内容:
- 第一行:
GB | Evri - 第二行:
USA | RoyalMail
内容的提问来源于stack exchange,提问作者CodeBee
相关产品推荐
相关产品推荐

