我正在学习 React 基础知识,并遇到了这个给我带来很多麻烦的挑战。
我有“状态”功能中的项目列表。当我在屏幕上列出它们时,我想列出具有“found=0”值的那些。我尝试在网络中搜索,尝试应用很多不同的解决方案,包括 stackoverflow 中的解决方案,但我不断收到很多不同的错误,所以我无法使其工作。
这是我保存在 App.js 文件中的“状态”函数:
state = {
counters: [
{ id: 1, title: "Soymilk", found: 1, value: 0 },
{ id: 2, title: "Mushroom", found: 0, value: 0 },
{ id: 3, title: "Tomatoes", found: 1, value: 0 },
{ id: 4, title: "Potatoes", found: 0, value: 0 },
{ id: 5, title: "Meat", found: 0, value: 0 },
{ id: 6, title: "Beans", found: 0, value: 0 },
{ id: 7, title: "Bread", found: 0, value: 0 }
]};
这是显示我的项目的 counter.jsx 代码:
render() {
return (
<div className="list-group">
<span className="font-weight-bold list-group-item list-group-item-action flex-column align-items-start">
{this.props.counter.title}
<span className="font-weight-normal text-secondary float-right">
{this.foundMessage()}
</span>
</span>
<div className="row">
<button
onClick={() => this.props.onFind(this.props.counter)}
className="btn btn-sm col-3 btn-primary col-6"
>
Found it!
</button>
<button
onClick={() => this.props.onDelete(this.props.counter.id)}
className="btn btn-danger btn-sm col-6"
>
No more needed!
</button>
</div>
</div>
);}}
最佳答案
您可以过滤数据,
像这样,
let filteredData= this.state.counters.filter(item=>item.found==0);
this.setState({counters:filteredData});
关于javascript - 如何在 React 中过滤屏幕上显示的数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55740083/