reactjs - 如何选择性地渲染反应表组件?
问题描述
在给定的代码片段中,如果标题等于 _id,我不想渲染组件,但以下条件渲染根本不会渲染(空表)。我应该使用什么条件语句?
return <table className='paleBlueRows' cellPadding= {11} cellSpacing={11}>
<thead>
<tr>{data[0] && columns.map((heading) => {
if(heading!=='_id') <th>{heading}</th>
})}</tr> .....
解决方案
您可以Array.filter()
在映射之前使用过滤掉标题,或者您可以返回null
或false
哪个React 将忽略。请注意,返回undefined
(与不从函数返回任何内容相同)是无效的,并且会导致 React 发出警告。
所以,要么:
return (
<table className="paleBlueRows" cellPadding={11} cellSpacing={11}>
<thead>
<tr>
{data[0] &&
columns
.filter((heading) => heading !== "_id")
.map((heading) => {
return <th>{heading}</th>;
})}
</tr>
</thead>
</table>
);
或者:
return (
<table className="paleBlueRows" cellPadding={11} cellSpacing={11}>
<thead>
<tr>
{data[0] &&
columns
.filter((heading) => heading !== "_id")
.map((heading) => {
if (heading === "_id") return null;
return <th>{heading}</th>;
})}
</tr>
</thead>
</table>
);
由于您正在渲染一个列表(使用.map()
),请确保您设置了key
从它返回的元素。我不知道是否columns
可以包含重复值,或者关于其性质的任何其他内容,所以我无法提出准确的建议。如果不包含重复值,只需将其值设置为键,以便 React 知道在渲染之间发生更改columns
时需要更新哪些元素。columns
return (
<table className="paleBlueRows" cellPadding={11} cellSpacing={11}>
<thead>
<tr>
{data[0] &&
columns
.filter((heading) => heading !== "_id")
.map((heading) => {
return <th key={heading}>{heading}</th>;
})}
</tr>
</thead>
</table>
);
推荐阅读
- angular - 无法将提交推送到远程 GitHub
- php - 关系和当前表的 Laravel 排序顺序
- javascript - MongoDB:如何使用对象数组更新许多对象,每个对象都有自己的_id?
- swift - 使用类级别的 if-let 快速检查 nil
- javascript - JSON 数据未填满 DataTable
- xslt-2.0 - 分组和计数数据
- assembly - 在 X86 程序集中打印未初始化的数据是否有特定的方法?
- json - 如何正确地从此 API 请求信息?
- video - 在FFmpeg中加入视频有问题超过1000帧重复
- python - Python中不同类型的二维数组