【发布时间】:2023-04-05 09:24:01
【问题描述】:
我是新手,正在尝试制作一个 todolist 网站,我已经完成了添加和删除和显示功能,只是尝试添加一个搜索功能,但我似乎无法让它工作,因为它没有过滤适当地。
我基本上希望能够使用搜索值过滤 todos.title 上的值。例如,如果我输入“ta”的值,它应该显示“取出垃圾”的待办事项项目或与该字符串匹配的任何项目。
当我尝试搜索时,它会随机输出过滤后的项目,我想知道我的过滤是否错误,或者我是否不喜欢正确显示。
我尝试将值传递到 todo.js 并在那里显示,但似乎这不是一种可行的方式,因为它应该保留在 App.js 中。
class App extends Component {
state = {
todos: [
{
id: uuid.v4(),
title: "take out the trash",
completed: false
},
{
id: uuid.v4(),
title: "Dinner with wife",
completed: true
},
{
id: uuid.v4(),
title: "Meeting with Boss",
completed: false
}
],
filtered: []
};
// checking complete on the state
markComplete = id => {
this.setState({
todos: this.state.filtered.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
return todo;
})
});
};
//delete the item
delTodo = id => {
this.setState({
filtered: [...this.state.filtered.filter(filtered => filtered.id !== id)]
});
};
//Add item to the list
addTodo = title => {
const newTodo = {
id: uuid.v4(),
title,
comepleted: false
};
this.setState({ filtered: [...this.state.filtered, newTodo] });
};
// my attempt to do search filter on the value recieved from the search field (search):
search = (search) => {
let currentTodos = [];
let newList = [];
if (search !== "") {
currentTodos = this.state.todos;
newList = currentTodos.filter( todo => {
const lc = todo.title.toLowerCase();
const filter = search.toLowerCase();
return lc.includes(filter);
});
} else {
newList = this.state.todos;
}
this.setState({
filtered: newList
});
console.log(search);
};
componentDidMount() {
this.setState({
filtered: this.state.todos
});
}
componentWillReceiveProps(nextProps) {
this.setState({
filtered: nextProps.todos
});
}
render() {
return (
<div className="App">
<div className="container">
<Header search={this.search} />
<AddTodo addTodo={this.addTodo} />
<Todos
todos={this.state.filtered}
markComplete={this.markComplete}
delTodo={this.delTodo}
/>
</div>
</div>
);
}
}
export default App;
搜索值来自作为道具传递值的标头。我已经检查过了,它工作正常。
Todos.js
class Todos extends Component {
state = {
searchResults: null
}
render() {
return (
this.props.todos.map((todo) => {
return <TodoItem key={todo.id} todo = {todo}
markComplete={this.props.markComplete}
delTodo={this.props.delTodo}
/>
})
);
}
}
TodoItem.js 只是显示项目的组件。
我不确定这是否足以 100% 理解问题,如果需要,我可以添加更多内容。
谢谢
【问题讨论】:
-
我看到的一个问题是您使用了“过滤器”javascript 函数。这不是你要找的。我会建议你这样做:
if (search) { return this.state.todos.map(todo => todo.match(`/${search.toLowerCase}/g`))} -
你完全混淆了过滤和待办事项状态
标签: reactjs filtering material-ui