gpt4 book ai didi

reactjs - 如何使用 .filter 在 Reactjs 中将过滤器添加到 todolist 应用程序

转载 作者:行者123 更新时间:2023-12-05 07:26:27 25 4
gpt4 key购买 nike

我是新手,正在尝试制作一个 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;

搜索值来自 header ,值作为 Prop 传递。我已经检查过了,它工作正常。

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% 理解问题,如果需要我可以添加更多内容。

谢谢

最佳答案

不确定您的脚本有什么问题。在我看来,当我尝试使用您的大部分逻辑进行重建时,它工作正常。请在此处查看工作演示:https://codesandbox.io/s/q9jy17p47j

我猜,可能是你的 <TodoItem/> 有问题使其无法正确呈现的组件。也许您可以尝试使用原始元素,例如 <li>而是像 <TodoItem/> 这样的自定义元素.问题可能出在您的 markComplete() 逻辑上事情(如果它正在做隐藏元素的工作)。

如果我遗漏了什么,请告诉我。谢谢。

关于reactjs - 如何使用 .filter 在 Reactjs 中将过滤器添加到 todolist 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54284307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com