为什么this.setState({ filteredStudents: newList });上的newList是空数组?
我正在创建一个简单的React.js应用程序,并试图创建一个输入框,从一组数据中“实时”过滤结果,实时控制页面上显示的内容。
过滤数据显示状态的步骤失败并清空状态。
除了处理此行为的代码部分之外,我已经确认了所有内容,以便在组件的其他地方正常工作。
我的函数,用于过滤和刷新"filteredStudents“状态(即连接到页面上显示的内容)。
然而,当页面触发此函数时,"newList“(第2行上的变量)为空,虽然页面没有失败,但"filteredStudents”状态现在为空。我假设这意味着我错误地实现了第7&8行中的".includes“步骤,但无法纠正它。
listFilter = () => {
let newList = [];
let search = this.state.search;
let list = this.state.filteredStudents;
if (this.state.search !== "") {
for (let i = 0; i > list.length; i++) {
let checkFirst = list[i].firstName.includes(search);
let checkLast = list[i].lastName.includes(search);
if (checkFirst === true || checkLast === true) {
newList.push(list[i]);
}
}
this.setState({ filteredStudents: newList });
} else {
let resetStudents = this.state.students;
this.setState({ filteredStudents: resetStudents });
}
}
我正在尝试或多或少地复制这个行为,就像我在这个例子中发现的那样:
https://codepen.io/pjmtokyo/pen/ZGVjVV
但我还没能做到。所编写的函数只是清空数组。我假设我在第7&8行的".includes“步骤的实现中有一个错误,但我还没能修复它。
转载请注明出处:http://www.wje4.com/article/20230526/1656734.html