为什么我的过滤器功能不起作用?

时间:2018-02-08 08:04:40

标签: javascript arrays reactjs filter

应该过滤列表的简单反应组件。不工作,我不明白为什么......

import React from 'react';

class Filter extends React.Component {
  state = {
    input: '',
    items: [{name: 'lol'}]
  }

  handleChange = (event) => this.setState({ input: event.target.value })

  render(){
    const { input, items } = this.state;
    return(
      <div>
        <input
          placeholder="search for an item"
          onChange={this.handleChange}
        />
        {items.filter(term => term.includes(input)).map((term) => (
          <div>{term.name}</div>
        ))}
      </div>
    )
  }
}

export default Filter;

逐字过滤数组,然后映射到它......

2 个答案:

答案 0 :(得分:0)

import React from 'react';

class Filter extends React.Component {
  state = {
    input: '',
    items: [{name: 'lol'}],
    filteredItems: false,
  } 

   filter(e) {
          var value = e.target.value;
          this.setState({filterval: value})

          this.setState({
            filteredItems: !value
              ? false
              : this.state.items.filter(function (item) {
                return item.name.toLowerCase().indexOf(value.toLowerCase()) !== -1;
              })
          })
        }


    render(){



            var list = this.state.filteredItems || this.state.items || []

            return (
             <div>
         <input placeholder="search for an item" onChange={this.filter.bind(this)}
        />
<div>

              {list.map((item,index) => (


                           <div>{term.name}</div>
                        ))}
</div>    
 </div>
 )

答案 1 :(得分:0)

items.filter(term => term.includes(input))

这里的情况不正确。变量term是一个对象{name: 'lol'}includes不适用于对象。 它应该是term.name.includes(input)term.name === input