我甚至不确定是否可以这样做,但我会试着解释我想要实现的目标。
我正在尝试筛选和映射一个数组,其中labels.attributes.label === this.state.currentLabel
我正在让它工作。但如果是this.state.currentLabel === 'All',我只想做.map,而不是.filter
有没有我可以实现的条件逻辑来让它工作?
这里是代码现在的样子:
{podcasts.filter((labels) => labels.attributes.label === this.state.currentLabel)
.map((pod) => {
const podId = pod.id.attributes['im:id']
const podName = pod['im:name'].label
return <PodcastItem key={podId} id={podId} name={podName} />
})}如果我解释得不好,很抱歉..我对编码是相当陌生的。所以,如果我能更好地描述它,请发表评论。
发布于 2018-10-12 03:37:24
只需将另一个条件添加到您的过滤器函数(使用||),您就完成了:
{podcasts.filter((labels) => this.state.currentLabel ===labels.attributes.label || this.state.currentLabel==='All')
.map((pod) => {
const podId = pod.id.attributes['im:id']
const podName = pod['im:name'].label
return <PodcastItem key={podId} id={podId} name={podName} />
})}发布于 2018-10-12 03:35:07
而不是像这样链接
let ans = data.filter(..)
.map(..)你可以做到
let filtered = data;
if( /* your state condition */) {
filtered = data.filter(...)
}
let ans = filtered.map(...)发布于 2018-10-12 03:35:46
你可以像这样内联它:
{podcasts
.filter(
labels =>
this.state.currentLabel === 'All'
? labels
: labels.attributes.label === this.state.currentLabel,
)
.map(pod => {
const podId = pod.id.attributes['im:id'];
const podName = pod['im:name'].label;
return <PodcastItem key={podId} id={podId} name={podName} />;
});
}https://stackoverflow.com/questions/52767607
复制相似问题