ReactJs中的.filter()函数

时间:2019-06-13 09:37:08

标签: reactjs

JSON请求调用了fetch(),如下所示:

[{
"Info": "",
"Val": "3"
},
{
"Info": "",
"Val": "5"
},
{
"Info": "",
"Val": "1"
},
{
"Info": "",
"Val": "1"
}]

我的目的是根据名为Val的文件过滤数据。

 library = library.filter(item =>
             item.Val==FilterVal
 )

让我举一个例子来说明我想做什么。 查看此输入:<input value={this.state.FilterVal} onChange={this.handlerFilter} />

FilterVal将是一个数字,例如1或一些用逗号1,5,4分隔的数字。 例如,用户在输入中输入1,结果必须返回Val1的对象。下次输入1,5,4时,必须将Val154的对象还给我。

这是我的一部分代码:

  class App extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
        data: [],
        library: null,
        FilterVal: "",

    }
}
componentDidMount() {
        fetch('/json.bc', {
            method: 'POST',
        })
            .then(response => response.text())
            .then(text => {
                const Maindata = JSON.parse(text.replace(/\'/g, '"'))
                 this.setState(state => ({
                    ...state,
                    data: Maindata
                }), () => {
                    this.reorganiseLibrary()
                })
            }).catch(error => console.error(error))
    })
}
reorganiseLibrary = () => {
    const { FilterVal} = this.state;
    let library = data;
    if (FilterVal !== "") {
        library = library.filter(item =>
             item.Val==FilterVal
        )
    }
    library = _.chunk(library);
    this.setState({
        library
    })

}

handlerFilter = evt =>
    this.setState(
        {
            FilterVal: evt.target.value
        },
        () => {
            this.reorganiseLibrary();
        }
    )
renderLibrary = () => {
const { library} = this.state;
    if (!library || (library && library.length === 0)) {
        return <div>nodata</div>
    }
return library.map((item, i) => (
        <div>
                  <span>{item.name}</span>
                  <span>{item.Val}</span>
       </div>
    ))
}

render() {
    const { library} = this.state;
    return (
        <div>
         {this.renderLibrary()}
         <input value={this.state.FilterVal} onChange={this.handlerFilter} />
      </div>
    )
}
}
ReactDOM.render(<App />, document.getElementById('Result')) 

2 个答案:

答案 0 :(得分:1)

只需调整您的过滤器:

const values = FilterVal.split(',').map(v => Number(v))
library = library.filter(item => values.includes(item.Val))

答案 1 :(得分:0)

您可以使用FilterVal.includes(item.Val)。这是有效的解决方案。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      library: null,
      FilterVal: ""
    };
  }
  componentDidMount() {
    var originalArray = [
      {
        Info: "",
        Val: "3"
      },
      {
        Info: "",
        Val: "3"
      },
      {
        Info: "",
        Val: "2"
      },
      {
        Info: "",
        Val: "4"
      },
      {
        Info: "",
        Val: "4"
      },
      {
        Info: "",
        Val: "5"
      },
      {
        Info: "",
        Val: "2"
      },
      {
        Info: "",
        Val: "1"
      }
    ];
    this.setState({ data: originalArray });
  }
  reorganiseLibrary = () => {
    let FilterVal = this.state.FilterVal;
    let library = this.state.data;
    if (FilterVal !== "") {
      FilterVal = FilterVal.split("");
      library = library.filter(item => {
        if (FilterVal.includes(item.Val)) return item;
      });
    } else {
      library = null;
    }
    // library = _.chunk(library);
    this.setState({
      library
    });
  };

  handlerFilter = evt =>
    this.setState(
      {
        FilterVal: evt.target.value
      },
      () => {
        this.reorganiseLibrary();
      }
    );
  renderLibrary = () => {
    const { library } = this.state;
    if (!library || (library && library.length === 0)) {
      return <div>nodata</div>;
    }
    return library.map((item, i) => (
      <div>
        <span>{item.name}</span>
        <span>{item.Val}</span>
      </div>
    ));
  };

  render() {
    const { library } = this.state;
    return (
      <div>
        {this.renderLibrary()}
        <input value={this.state.FilterVal} onChange={this.handlerFilter} />
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("Result"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='Result' />