Javascript 如何在react js中过滤ToDo应用程序中的数组
我是新手。我创建了一个简单的todo应用程序,它将数据存储在一个数组中。我还添加了分页和删除选项。现在我想添加一个搜索字段。当类型输入显示错误时,我添加了一个输入字段: TypeError:item.toLowerCase不是函数 我的代码:Javascript 如何在react js中过滤ToDo应用程序中的数组,javascript,reactjs,filter,Javascript,Reactjs,Filter,我是新手。我创建了一个简单的todo应用程序,它将数据存储在一个数组中。我还添加了分页和删除选项。现在我想添加一个搜索字段。当类型输入显示错误时,我添加了一个输入字段: TypeError:item.toLowerCase不是函数 我的代码: import React, { Component } from 'react' class Search extends Component{ constructor(props){
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
import React,{Component}来自“React”
类搜索扩展组件{
建造师(道具){
超级(道具)
此.state={
过滤:[]
}
this.handleChange=this.handleChange.bind(this);
}
componentDidMount(){
这是我的国家({
筛选:this.props.listItems//props来自其他页面
});
}
组件将接收道具(下一步){
这是我的国家({
过滤:nextrops.listItems
});
}
手变(e){
//变量来保存列表的原始版本
让currentList=[];
//变量,用于在进入状态之前保存筛选列表
让newList=[];
//如果搜索栏不是空的
如果(例如,target.value!==“”){
//将原始列表分配给currentList
currentList=this.props.listItems;
//使用.filter()确定应显示哪些项目
//基于搜索词
newList=currentList.filter(项=>{
//将当前项更改为小写
const lc=item.toLowerCase();
//将搜索词更改为小写
const filter=e.target.value.toLowerCase();
返回信用证。包括(过滤器);
});
}否则{
//如果搜索栏为空,请将newList设置为原始任务列表
newList=this.props.listItems;
}
//根据规则添加到newList的内容设置筛选状态
这是我的国家({
过滤:新列表
});
}
render(){
返回(
{this.props.btton}
{this.props.listItems}
);
}
}
导出默认搜索
您是否尝试在筛选过程中检查is项目?请尝试控制台。记录结果或调试。我猜item不是您期望的对象,这就是您看到错误的原因。@SajidAli我们不是来修复您的代码的。我们在这里帮助您了解问题所在。您是否按照tomerpacific的要求进行了调试?@SajidAlicurrentList
数组的外观如何?介意寄个样品吗?