我有一个简单的组件,它从一组对象构建报告列表,我正在尝试添加过滤和排序功能(在一定程度上确实有效),排序功能有效,但我担心我正在变异尽管试图将原始状态复制到新数组中。
我的过滤器第一次工作,但它不会过滤其他结果,因为状态已经发生变化,或者因为我无法过滤初始状态?这让我困惑了几个小时,非常感谢任何帮助。
非常感谢
constructor(props) {
super(props);
this.state = {
reports: props.data
};
this.handleSortBy = this.handleSortBy.bind(this);
this.handleFilterType = this.handleFilterType.bind(this);
}
handleSortBy(event) {
const copy = [...this.state.reports];
if (event.target.value === 'A-Z') {
return this.setState({
reports: copy.sort((a, b) => a.name.localeCompare(b.name))
});
}
if (event.target.value === 'Z-A') {
this.setState({
reports: copy
.sort((a, b) => a.name.localeCompare(b.name))
.reverse()
});
}
}
handleFilterType(event) {
this.setState({
reports: this.state.reports.filter(item => {
return item.type === event.target.value;
})
});
}
提前致谢 :)