我什至不确定是否可以这样做,但是我将尽力解释我想要完成的事情。
我正在尝试过滤和映射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} />
})}
很抱歉,如果我不善于解释。.我是编码的新手。因此,如果我能更好地描述它,请发表评论。
答案 0 :(得分:2)
代替
let ans = data.filter(..)
.map(..)
你可以做
let filtered = data;
if( /* your state condition */) {
filtered = data.filter(...)
}
let ans = filtered.map(...)
答案 1 :(得分:1)
您可以这样内联:
{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} />;
});
}
答案 2 :(得分:1)
只需向过滤器功能添加另一个条件(使用||
),就可以完成:
{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} />
})}