javascript - 如何在 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
解决方案
推荐阅读
- react-native - 哪个 react-native 版本支持所有 npms?
- visual-studio-cordova - VS Tools for Cordova 覆盖 Android 图标
- mongodb - Mongo DB 或任何 nosql DB(Hbase、Cassandra)如何比传统的 RDBMS 具有可扩展性和优势?
- php - 使用 Laravel 的 Eloquent 构建查询
- c++ - 从指针基抽象类调用非虚拟子类方法
- java - JCIFS SMB 库 - 尝试列出域 (.listFiles) 时出错
- ios - ARKit 3D 模型的最佳设置是什么
- compilation - 如何检测 F# 程序是在 Mono 上编译的?
- javascript - 在 VueJs 中过滤数据 - Vuetify v-tabs
- reactjs - 在固定数据表 2 中导入 CSS 文件时出错