简体   繁体   English

使用按钮过滤对象数组

[英]Filtering an array of objects with a button

React newbie here is asking for some help. React 新手在这里寻求帮助。 Here is the deal: I have an array of 4 objects (in my Data.js file) and, after clicking on a button, I want to display only the items belonging to "category A" in my example below.这是交易:我有一个包含 4 个对象的数组(在我的Data.js文件中),并且在单击按钮后,我想在下面的示例中仅显示属于“类别 A”的项目。 I'm a bit confused with the use of setState (which I assume I would need since my button will "update" the initial state to only reflect the data I want to display (hence item 1 and 4). Any ideas how it can be done? Cheers!我对 setState 的使用有些困惑(我认为我需要它,因为我的按钮将“更新”初始状态以仅反映我想要显示的数据(因此是第 1 项和第 4 项)。任何想法如何完成了吗?干杯!

index.js索引.js

import React, {Component} from "react";
import ReactDOM from "react-dom";
import Data from "./Data.js";



class Root extends Component {
    constructor(props) {
        super(props);
        this.state = {
            items: Data,
        }
    }

myFunctionA = () => {
    // filtering in here
}
    
render() {
        return (
            <div>
                <button onClick={this.myFunctionA}>Click me to display item 1 & 4</button>
            </div>
            
        )
    }
}

ReactDOM.render(<Root />, document.getElementById("root"))

Data.js数据.js

const Data = [
  {
    "id": 1,
    "name": "First item",
    "category": "A"
  },
  {
    "id": 2,
    "name": "Second item",
    "category": "B"
  },
  {
    "id": 3,
    "name": "Third item",
    "category": "C"
  },
  {
    "id": 4,
    "name": "Fourth item",
    "category": "A"
  },
]

export default Data

You're right, you need to use setState.你是对的,你需要使用 setState。

Try something like that:尝试这样的事情:

myFunctionA = () => {
    const filteredData = this.state.items.filter(elem => elem.category === 'A');
    this.setState({ items: filteredData });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM