首页 > 解决方案 > 如何在 React js 中过滤 ToDo App 中的数组

问题描述

我是 React Js 的新手。我创建了一个简单的待办事项应用程序,它将数据存储在一个数组中。我还添加了分页和删除选项。现在我想添加一个搜索字段。我在输入类型时添加了一个输入字段,它们向我显示错误:

TypeError:item.toLowerCase 不是函数

我的代码:

    import React, { Component } from 'react'
    class Search  extends Component{
            constructor(props){
                super(props)
                this.state = {
                    filtered: []
                }
                this.handleChange = this.handleChange.bind(this);
            }
            componentDidMount() {
                this.setState({
                  filtered: this.props.listItems  //props from other page
                });
              }
              componentWillReceiveProps(nextProps) {
                this.setState({
                  filtered: nextProps.listItems
                });
              }
              handleChange(e) {
                // Variable to hold the original version of the list
            let currentList = [];
                // Variable to hold the filtered list before putting into state
            let newList = [];

                // If the search bar isn't empty
            if (e.target.value !== "") {

                    // Assign the original list to currentList
              currentList = this.props.listItems;

                    // Use .filter() to determine which items should be displayed
                    // based on the search terms
              newList = currentList.filter(item => {

                // change current item to lowercase
                const lc = item.toLowerCase();

                // change search term to lowercase
                const filter = e.target.value.toLowerCase();
                return lc.includes(filter);
              });
            } else {
                    // If the search bar is empty, set newList to original task list
              newList = this.props.listItems;
            }
                // Set the filtered state based on what our rules added to newList
            this.setState({
              filtered: newList
            });
          }
        render() {
            return (
                <div>
                     <input type="text" className="input" onChange={this.handleChange} 
                     placeholder="Search..." />
                    {this.props.btton}
                    {this.props.listItems}

                </div>
            );
        }
    }
    export default Search

标签: javascriptreactjsfilter

解决方案


推荐阅读