javascript - React Search Box 在添加文本时工作良好但在向后方向不工作(当通过退格键删除一些文本时)-ReactJS/Javascript

标签 javascript reactjs

这是我的演示项目 - Demo .我正在使用 react 表。我正在尝试创建一个自定义框,它只能过滤第一列 - firstName。根据第一列搜索,将显示其他列的相应行。

当我们添加字符时过滤器工作得很好,但是一旦我们开始删除字符过滤就不会发生 Demo

这是主代码(父页面)

import React from "react";
import { render } from "react-dom";
import TypeChecker from "typeco";
// import matchSorter from "match-sorter";
import SearchField from "./SearchField";
import "./App.css";

import Child from "./Child/Child";
import jsondata from "./sample";

// Import React Table
import ReactTable from "react-table";
import "react-table/react-table.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      // data: makeData(),
      data: jsondata,
      dataDefault: jsondata,
      basicExampleList: jsondata,
      filtered: [],
      select2: null,
      select3: null,
      childOpen: false
    };
    this.openChild = this.openChild.bind(this);
    this.applyFilter = this.applyFilter.bind(this);
    this.showDefaultView = this.showDefaultView.bind(this);
    this.onBasicExampleChange = this.onBasicExampleChange.bind(this);
    this.onEnterExample = this.onEnterExample.bind(this);
    this.onSearchClickExample = this.onSearchClickExample.bind(this);
    this.getMatchedList = this.getMatchedList.bind(this);
  }

  getMatchedList(searchText) {
    console.log("getMatchedList entered");
    console.log("the search text is " + searchText);
    const exampleList = this.state.basicExampleList;
    if (TypeChecker.isEmpty(searchText)) {
      console.log(
        "if block of getMatchedList - > TypeChecker.isEmpty(searchText) " +
          TypeChecker.isEmpty(searchText)
      );
      this.setState({ basicExampleList: exampleList });
      return this.state.basicExampleList;
    }
    if (!TypeChecker.isEmpty(searchText)) {
      console.log("if block of getMatchedList is not entered ");
      return exampleList.filter(
        item =>
          item.firstName.includes(searchText) ||
          item.firstName.includes(searchText)
      );
    }
  }

  onBasicExampleChange(value) {
    console.log("onchange entered");
    console.log(" the value is " + value);
    this.setState({
      basicExampleList: this.getMatchedList(value)
    });
  }

  onEnterExample(value) {
    this.setState({
      basicExampleList: this.getMatchedList(value)
    });
  }

  onSearchClickExample(value) {
    this.setState({
      basicExampleList: this.getMatchedList(value)
    });
  }

  applyFilter(filtered) {
    console.log("Entering Apply Filter Function of Parent");
    console.log("The filtered data in parent " + JSON.stringify(filtered));
    const currentStateChild = this.state.childOpen;
    this.setState(
      {
        childOpen: !currentStateChild
      },
      () => {
        console.log("Child is opened " + this.state.childOpen);
      }
    );
    const filterArray = filtered;
    const apidata = this.state.data;
    let filteredData = apidata.filter((
      item // filter jsondata
    ) =>
      filterArray.every((
        f // so every member of filter array
      ) => f.value.includes(item[f.id]))
    ); // has a corresponding item[id] in value

    console.log("The filtered rows are " + JSON.stringify(filteredData));
    this.setState(
      {
        data: filteredData
      },
      () => {
        console.log("Manipulated rows " + this.state.data);
      }
    );
  }

  openChild() {
    const currentStateChild = this.state.childOpen;
    this.setState(
      {
        childOpen: !currentStateChild
      },
      () => {
        console.log("Child is opened " + this.state.childOpen);
      }
    );
  }

  showDefaultView() {
    const defaultDataParent = this.state.dataDefault;
    this.setState(
      {
        data: defaultDataParent
      },
      () => {
        console.log("Default rows " + this.state.data);
      }
    );
  }

  render() {
    const { data } = this.state;
    return (
      <div>
        <div className="clickMeToOpenChild" onClick={this.openChild}>
          {" "}
          Click Me to Open Child
        </div>
        <div className="clickMeToGetDefaultView" onClick={this.showDefaultView}>
          {" "}
          Click Me to show Default View
        </div>
        <br />
        <SearchField
          placeholder="Search item"
          onChange={this.onBasicExampleChange}
          onEnter={this.onEnterExample}
          onSearchClick={this.onSearchClickExample}
        />
        <br />
        <br />
        <ReactTable
          data={this.state.basicExampleList}
          filterable
          filtered={this.state.filtered}
          onFilteredChange={(filtered, column, value) => {
            this.onFilteredChangeCustom(value, column.id || column.accessor);
          }}
          defaultFilterMethod={(filter, row, column) => {
            const id = filter.pivotId || filter.id;
            if (typeof filter.value === "object") {
              return row[id] !== undefined
                ? filter.value.indexOf(row[id]) > -1
                : true;
            } else {
              return row[id] !== undefined
                ? String(row[id]).indexOf(filter.value) > -1
                : true;
            }
          }}
          columns={[
            {
              Header: "Name",
              columns: [
                {
                  Header: "First Name",
                  accessor: "firstName"
                },
                {
                  Header: "Last Name",
                  id: "lastName",
                  accessor: d => d.lastName
                }
              ]
            },
            {
              Header: "Info",
              columns: [
                {
                  Header: "Age",
                  accessor: "age"
                }
              ]
            }
          ]}
          defaultPageSize={10}
          className="-striped -highlight"
        />
        {this.state.childOpen && (
          <Child data={data} applyFilter={this.applyFilter} />
        )}
        <br />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

请帮我解决这个问题。

最佳答案

问题是您正在覆盖真实数据,因此如果您进行搜索但没有结果,它最终会变成空的。

固定码here .

关于javascript - React Search Box 在添加文本时工作良好但在向后方向不工作(当通过退格键删除一些文本时)-ReactJS/Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051790/

相关文章:

javascript - 通过 Props 将值从 React Stateless Child 传递给 Parent

javascript - 嵌套同名Div,一键选择正确的

javascript - 单击按钮将页面滚动到嵌套的 React 组件

javascript - 下一次 safari 的发布日期

javascript - 在 React 中渲染 child ,丢失 Prop 数据

javascript - 如何在不重新加载页面的情况下将服务器端重定向到其他页面并且仍然将 URL 保留在 Nextjs 应用程序中?

javascript - 如何从后端获取数据

animation - React 中的动画页面转换

reactjs - 如果我有catch(),我是否需要在promise链的末尾调用done()?

javascript - 与对象解构相反