【发布时间】:2020-11-02 12:07:15
【问题描述】:
我正在用 React 构建一个小型服装店应用程序,只是为了学习一些东西。我实现了按价格部分的过滤器,但我希望能够为所选价格范围内没有商品的情况编写条件,而不是页面为空白。
render() {
const filteredOpt2 = this.state.items.filter(item => item.price <= 60);
const filteredOpt3 = this.state.items.filter(item => item.price >= 60 && item.price <= 100);
return (
<div>
{
this.state.selectedOption === "option1"
? <ProductList products={this.state.items} style={{marginLeft: 0}}/>
: this.state.selectedOption === "option2"
? <ProductList products={filteredOpt2} style={{marginLeft: 0}}/>
: this.state.selectedOption === "option3"
? <ProductList products={filteredOpt3} style={{marginLeft: 0}}/>
: null
}
</div>
)
}
我知道代码非常重复并且确实不理想,但我现在想不出更好的方法。
所以我想做的是,假设filteredOpt2导致一个空数组,我如何以及在哪里实现一个条件,如果发生这种情况,显示一个显示文本的p标签?
【问题讨论】:
标签: javascript reactjs conditional-operator conditional-rendering