[英]Add edit todo function and update state correctly in react todo app
I have the following component which adds a todo to my todo list. 我有以下组件,它为我的待办事项列表添加了待办事项。 The todo's are not displaying in input field but was thinking I can run onclick function if button is clicked then I can edit the existing todo.
todo没有在输入字段中显示,但是如果点击按钮我想可以运行onclick功能然后我可以编辑现有的待办事项。
Here is what I have started with, I just need some guidance where to go from here. 这是我的开始,我只需要一些指导从哪里开始。 At the moment when I click on the edit todo button it adds another item but not editing the existing one.
当我点击编辑待办事项按钮时,它会添加另一个项目,但不会编辑现有项目。 I have suspicion I am not editing the state as I am supposed to.
我怀疑我没有像我应该的那样编辑国家。
My edit todo function: 我的编辑待办事项功能:
editTodo = (title) => {
console.log("Edit todo:" + title)
const editTodo = {
title:title,
edited: false
}
this.setState({ todos: [
...this.state.todos, editTodo
]
});
}
My edit button next to todo item: todo项旁边的我的编辑按钮:
<button className="edit-btn" onClick={this.props.editTodo.bind(this, id)}>EDIT</button>
My edit todo component 我的编辑待办事项组件
class EditTodo extends Component {
state = {
edited: false
}
onSubmit = (e) => {
e.preventDefault();
this.props.editTodo(this.state.title);
this.setState({ title: ''});
}
onChange = (e) =>
this.setState({
[e.target.name]: e.target.value
}
);
render() {
return (
<form onSubmit={this.onSubmit}>
<input
type="text"
name="title"
placeholder="Edit Your Todo"
value={this.state.title}
onChange={this.onChange}
/>
<button
type="submit">
Edit
</button>
</form>
)
}
}
Update: 更新:
I made some changes, implemented a fake backend and reviewed this again and it makes sense to use the same logic as the delete function, how can I change the following to edit my current todo: 我做了一些更改,实现了一个虚假的后端,并再次审查了这一点,使用与删除功能相同的逻辑是有意义的,如何更改以下内容来编辑我当前的待办事项:
Here is my delete todo function 这是我的删除待办事项功能
deleteTodo = (id) => {
axios.delete(`http://localhost:3004/todos/${id}`)
.then(res => this.setState({
todos: [
...this.state.todos.filter(todo =>
todo.id !== id
)]
}));
}
``
The approach I followed initially was not working. 我最初遵循的方法不起作用。 Ref's solved my problem, the final solution posted here: edit todo list state not passed correctly in react with axios
Ref解决了我的问题,这里发布的最终解决方案: 编辑待办事项列表状态未正确传递与axios做出反应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.