Javascript 如何将此过滤器集成到我的代码中?

Javascript 如何将此过滤器集成到我的代码中?,javascript,Javascript,我有一些使用Fetch方法从数组中获取的名称列表。现在,我正在使用searchHandler方法,只需单击一个按钮,即可将输入数据输入控制台: 但我需要输入“First name”,然后点击按钮,只显示一行具有该名称的内容。但我不知道如何自己制作过滤器。 我在互联网上找到了解决方案,但不幸的是,我无法将其集成到我的代码中。这是: getFilteredData() { if (!this.state.search){ return this.state.data

我有一些使用Fetch方法从数组中获取的名称列表。现在,我正在使用searchHandler方法,只需单击一个按钮,即可将输入数据输入控制台:

但我需要输入“First name”,然后点击按钮,只显示一行具有该名称的内容。但我不知道如何自己制作过滤器。
我在互联网上找到了解决方案,但不幸的是,我无法将其集成到我的代码中。这是:

getFilteredData() {
    if (!this.state.search){
        return this.state.data
    }
    return this.state.data.filter(item=>{
        return item["firstName"].toLowerCase().includes(this.state.search.toLowerCase())
    });
}

如何将其集成到我的代码中?以及在render方法中写入什么?

由于您获取的数据是一个对象数组,并且您基本上希望筛选出与serach条件匹配的对象,下面是如何编写搜索处理程序:

  searchHandler = search => {
    const { data } = this.state;
    const filteredData = {
      group: {
        first: Object.values(data.group.first).filter(item => item.firstName.includes(search)),
      }
    }
    this.setState({ data: filteredData });
  };
基本上,它所做的是从数据中取出对象数组,只过滤出那些具有您搜索的名称的对象。并将过滤后的对象数组设置为与原始数据对象相同的结构,就这样!!
此外,现在不必对渲染方法进行任何更改。因为render方法已经在使用包含数据的状态。一旦您进入搜索状态,数据将被更新并在渲染中可用。

您在那里的方向是正确的。正确的代码(带有解释更改的注释)应为:

searchHandler = search => {
    // This if checks if search is empty. In that case, it reset the data to print the initial list again
    if (search) {
        // This 'arr' variable is a copy of what you do in your Table.js
        const arr = this.state.data.group && this.state.data.group.first ? this.state.data.group.first : this.state.data;
        const filteredArr = arr.filter((item) => {
            // Here you compare with 'search' instead of 'state.search', since you didn't updated the state to include the search term
            return item["firstName"].toLowerCase().includes(search.toLowerCase())
        })
        // This will update your state, which also updates the table
        this.setState({data: filteredArr})
    } else {
        // As explained, if search was empty, return everything
        this.resetData();
    }
};

// This is a copy of what you have in componentDidMount
async resetData() {
    const response = await fetch("/data/mass.json");
    const data = await response.json();
    this.setState({
        data
    });
}

注:
如您所见,并非所有浏览器都支持包含。如果您需要更可靠的解决方案,可以使用
indexOf
,如前所述。

您应该将代码包含在要将其集成到question@NinaScholz你这是什么意思?你能把你建议的代码放到我的沙箱里吗?因为当我插入我的组件时,这里的didmount是:
async resetData(){const response=await fetch(“/data/mass.json”);const data=await response.json();this.setState({data});}
,这显示了一个错误。我无法删除componentDidMount,因为我出于某种目的需要它这里是更新的链接: