首页 > 解决方案 > 根据 searchString 和产品大小过滤产品

问题描述

我对 React 还很陌生,还在学习。我正在尝试根据搜索字符串和/或使用基于尺寸状态的过滤器来过滤我的产品概览。

现在,搜索工作,我可以在这个产品视图中搜索 在此处输入图像描述 在此处输入图像描述

我的搜索是这样进行的:我从输入中获取值并将其插入{this.state.plants.filter您可以在下面的示例代码底部看到的值。

我的问题是:如何同时按this.state.sizeAND过滤产品this.state.searchString

或:留空this.state.searchString,只申请this.state.size

我希望我的问题是有道理的。

this.state = {
    plants: '',
    title: '',
    size: '',
    searchString: '',
    filterSize: ''
};
    
handleSearch = (event) => {
    this.setState({
        searchString: event.target.value
    })
}

handleSizeFilter = (event) => {
    this.setState({
        filterSize: event.target.value
    })
}
    
// Search input
<input type="text" className="search" placeholder="Søg" onChange={this.handleSearch} value={this.state.searchString} />
        
// Size Filter Button
<button onClick={handleSizeFilter} value="22">Size 22</button>
        
{this.state.plants.filter(plant => plant.title.includes(this.state.searchString)).map(plant => (
    {plant.title} - {plant.size}
))}

标签: reactjs

解决方案


我会在这里做的是:

let filteredPlants = this.state.plants;
const { searchString, filterSize } = this.state;

if (searchString) {
  filteredPlants = filteredPlants.filter(plant => plant.title.includes(searchString);
}

if (typeof filterSize === 'number') {
  filteredPlants = filteredPlants.filter(plant => plant.size === filterSize);
}

注意:由于这可能是一项昂贵的操作,具体取决于您的数组有多大,最好在类组件中创建一个方法并将其包装在一个实用程序函数中,如memoizeOne

如果你把它放在你的render方法中,每次你重新渲染时组件都会遍历数组 - 所以在你的情况下,每次你在输入字段中键入或删除一些东西


推荐阅读