在Reactjs中,如何过滤基于逗号分隔的某些项目上的数据?

时间:2019-06-13 07:22:01

标签: reactjs

我有JSON请求调用了fetch()

[{
    "name": "",
    "value": "1"
 },
 {
    "name": "",
    "value": "3"
 },
 {
    "name": "",
    "value": "2"
 },
 {
    "name": "",
    "value": "4"
 },
 {
    "name": "",
    "value": "4"
 },
 {
    "name": "",
    "value": "5"
  },
  {
    "name": "",
    "value": "2"
  },
  {
    "name": "",
    "value": "5"
  }]

我想根据名为value的文件过滤数据。 value将是一个数字,例如1或一些用逗号1,5,4分隔的数字。我想说的是过滤数据{item.value}所包含的内容value value为空时,向我显示所有数据。我这样写:

       library = library.filter(item =>
             item.value==Filtervalue
        )

但是它仅在我在value1中有一个数字并且对逗号1,5,4分隔的某些数字不起作用时才过滤数据。 这是我的一部分代码:

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

    }
}
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 { Filtervalue} = this.state;
    let library = data;
    if (Filtervalue !== "") {
        library = library.filter(item =>
             item.value==Filtervalue
        )
    }
    library = _.chunk(library);
    this.setState({
        library
    })

}

handlerFilter = evt =>
    this.setState(
        {
            Filtervalue: 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.realname}</span>
                  <span>{item.value}</span>
       </div>
    ))
}

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

0 个答案:

没有答案