我有字符串数组,由于输入值,我需要过滤该数组。我通过过滤器功能对其进行过滤,但是当我清除输入后,阵列将保持过滤状态。如何获得初始数组?
filterCoins = (e) => {
let updatedList = this.state.data;
updatedList = updatedList.filter(function(item){
return item.toLowerCase().search(
e.target.value.toLowerCase()) !== -1;
});
this.setState({data: updatedList});
};
答案 0 :(得分:0)
解决方案取决于您如何获取初始数据。
如果来自props
,最好将其放入state
中以填充filteredList
。
updatedList = this.props.data.filter(function(item){
return item.toLowerCase().search(
e.target.value.toLowerCase()) !== -1;
});
如果它是独立的状态组件,则使用类变量this.data
存储初始数据,以过滤this.data
中搜索到的项目;
updatedList = this.data.filter(function(item){
return item.toLowerCase().search(
e.target.value.toLowerCase()) !== -1;
});
this.setState({data: updatedList});
因此,建议总是从原始列表中过滤掉。
答案 1 :(得分:0)
每当更改输入值时,原始data
的状态当前正在被替换。
这意味着您要么需要保持旧数据的状态,以便在清除输入后可以恢复到原来的数据,要么采用另一种方式来实现。
当输入值更改时,我会将输入值设置为状态,而不是更新数据。
setCoinFilter = (e) => {
this.setState({ filterText: e.target.value });
}
然后在组件中渲染项目;可以执行过滤操作。
state = {
data: [],
filterText: '',
}
filterCoins(coins, filterText) {
return coins.filter(function(coin) {
return coin.toLowerCase(filterText.toLowerCase()).search() !== -1;
});
}
shouldNotApplyFilter() {
const { filterText } = this.state;
return filterText === null || filterText === '';
}
render() {
const data = this.shouldNotApplyFilter() ? this.state.data :
filterCoins(this.state.data, this.state.filterText)
// render data
}
答案 2 :(得分:0)
清除输入后,e.target.value
将为空,然后需要将this.state.data
重置为其原始值。我假设原始值保持不变,因此您可以像这样编写filtercoins
函数
filterCoins = (e) => {
let newData;
if (e.target.value) {
newData = this.state.data.filter(item =>
item.toLowerCase().indexOf(e.target.value.toLowerCase()) !== -1
);
} else {
newData = this.state.originalData;
}
this.setState({data: newData});
};