react js中如何根据filter选项显示指定的table行数据

How to show the specified table row data based on the filter option in react js

我是 reactjs 的新手。我在 table 中显示 json 数据。我还想针对特定筛选选项仅显示特定 table 行数据。 在这里,当我选择诺伊达时,table只能显示table的2 nd第三行。 选择莫拉达巴德时,它应该仅显示table的第一行。

我在这里附上显示所有行的图像,请帮助我在这个过滤逻辑中只显示选定的城市。

代码如下

    import React from 'react';
    import './style.css';
    
    export default class JsonDataDisplay extends React.Component {
     
     constructor(props) {
        super(props);
        this.state = {
          data: [
            {
              id: 1,
              name: 'Akshit',
              city: 'Moradabad',        
            },
    
            {
              id: 2,
              name: 'Nikita',
              city: 'Noida',
            },
    
            {
              id: 3,
              name: 'Deeksha',
              city: 'Noida',
             }
          ],
        };
      }
      render() {
        const displaydata = this.state.data.map((info) => (
          <tr>
            <td>{info.id}</td>
            <td>{info.name}</td>
            <td>{info.city}</td>
          </tr>
        ));
    
        return (
          <>
            <FilterComponent />
            <br />
            <section>
              <table>
                <thead>
                  <tr>
                    <th>id</th>
                    <th>name</th>
                    <th>city</th>  
                  </tr>
                </thead>
                <tbody>{displaydata}</tbody>
              </table>
            </section>
          </>
        );
      }
    }
    
    
    
    function FilterComponent(props) {
      const data = ['All', 'Noida', 'Moradabad'];
      return (
        <div>
          <div>city</div>
          <select>
            {data.map((field) => (
              <option>{field}</option>
            ))}
          </select>
        </div>
      );
    }

还有一些事情要做,

  1. 定义另一个状态变量来保持selectedCity状态
    this.state = {
      data: [
         ...
         ...
      ],
      selectedCity: "All"
    };
  1. 定义一个 onChange 处理函数来设置所选城市
  setSelectedCity = (selectedCity) => {
    this.setState({ selectedCity });
  };
  1. displaydata 添加过滤器,如下所示
const displaydata = this.state.data
      .filter(
        ({ city }) =>
          this.state.selectedCity === "All" || this.state.selectedCity === city
      )
      .map((info) => (
        <tr>
          <td>{info.id}</td>
          <td>{info.name}</td>
          <td>{info.city}</td>
        </tr>
      ));
  1. setSelectedCity 作为道具传递给 FilterComponent
<FilterComponent setSelectedCity={this.setSelectedCity} />
  1. 更新 FilterComponent 以在选择更改时设置 selectedCity
function FilterComponent({ setSelectedCity }) {
  const data = ["All", "Noida", "Moradabad"];
  return (
    <div>
      <div>city</div>
      <select onChange={(e) => setSelectedCity(e.target.value)}>
        {data.map((field) => (
          <option value={field}>{field}</option>
        ))}
      </select>
    </div>
  );
}

Code Sandbox