我的数据库中有一些记录,并不是所有的记录都有标记,有些记录可能是空的,它们存储在CosmosDb上,并以Json数组的形式返回。
我使用的是antd表和标签:https://ant.design/components/table/
示例:标签
我有以下代码:
import React, { Component } from 'react';
import { Table, Tag} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';
class ListPageTemplatesWithSelection extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
fetchData = () => {
adalApiFetch(fetch, "/PageTemplates", {})
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
const results= responseJson.map(row => ({
key: row.Id,
Name: row.Name,
SiteType: row.SiteType,
Tags: row.Tags
}))
this.setState({ data: results });
}
})
.catch(error => {
console.error(error);
});
};
componentDidMount(){
this.fetchData();
}
render(){
const columns = [
{
title: 'Id',
dataIndex: 'key',
key: 'key',
},
{
title: 'Name',
dataIndex: 'Name',
key: 'Name',
},
{
title: 'Site Type',
dataIndex: 'SiteType',
key: 'SiteTy[e',
},{
title: 'Tags',
key: 'Tags',
dataIndex: 'Tags',
render: Tags => (
<span>
{Tags.map(tag => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return <Tag color={color} key={tag}>{tag.toUpperCase()}</Tag>;
})}
</span>
),
}
];
const rowSelection = {
selectedRowKeys: this.props.selectedRows,
onChange: (selectedRowKeys) => {
this.props.onRowSelect(selectedRowKeys);
}
};
return (
<Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} />
);
}
}
export default ListPageTemplatesWithSelection;然而,我有这个错误:
58 | dataIndex: 'Tags',
59 | render: Tags => (
60 | <span>
> 61 | {Tags.map(tag => {
62 | let color = tag.length > 5 ? 'geekblue' : 'green';
63 | if (tag === 'loser') {
64 | color = 'volcano';我不确定这个错误是因为某些行没有标签,还是因为不同的原因,总之,我不确定我应该做些什么来避免这个错误。
发布于 2019-02-28 16:55:54
如果标签可能为空,则必须添加校验,以便不会在其上进行映射以进行渲染
<span>
{Tags && Tags.map(tag => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return <Tag color={color} key={tag}>{tag.toUpperCase()}</Tag>;
})}
</span>发布于 2019-02-28 17:04:26
您可以尝试在映射标签之前检查标签是否存在
render: Tags => (
<span>
{ Tags ? Tags.map(tag => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return <Tag color={color} key={tag}>{tag.toUpperCase()}</Tag>;
})
: ''}
</span>
)https://stackoverflow.com/questions/54921703
复制相似问题