单击delete按钮时,我一直试图删除待办事项,但浏览器却抛出一个运行时错误:"TypeError: props.deleteTodo不是函数“
我也双重检查了方法名,它们匹配,我不知道为什么onclick函数没有被识别。任何帮助都将不胜感激。
这是我的密码:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
const Todo = props => (
<tr>
<td className={props.todo.todo_status === "Completed" ? 'completed' : props.todo.todo_status === "In Progress" ? 'inprogress' : ''}>{props.todo.todo_desc}</td>
<td className={props.todo.todo_status === "Completed" ? 'completed' : props.todo.todo_status === "In Progress" ? 'inprogress' : ''}>{props.todo.todo_responsible}</td>
<td className={props.todo.todo_status === "Completed" ? 'completed' : props.todo.todo_status === "In Progress" ? 'inprogress' : ''}>{props.todo.todo_priority}</td>
<td className={props.todo.todo_status === "Completed" ? 'completed' : props.todo.todo_status === "In Progress" ? 'inprogress' : ''}>{props.todo.todo_status}</td>
<td className={props.todo.todo_status === "Completed" ? 'completed' : props.todo.todo_status === "In Progress" ? 'inprogress' : ''}>
<Link to={'/edit/' + props.todo._id}>Edit</Link> 
<button type="button" className="btn-danger" onClick={() => { props.deleteTodo(props.todo._id); }}>Delete</button>
</td>
</tr>
)
export default class TodoList extends Component {
constructor(props) {
super(props);
this.deleteTodo = this.deleteTodo.bind(this);
this.state = { todos: [] };
}
componentDidMount() {
axios.get('http://localhost:8082/todos/')
.then(res => {
this.setState({ todos: res.data })
})
.catch(function (error) {
console.log(error);
});
};
deleteTodo = (id) => {
axios.delete("http://localhost:8082/todos/delete/" + id)
.then(res => {
console.log(res.data)
this.props.history.push("/");
})
.catch(err => {
console.log("Error Deleting Todo");
})
};
componentDidUpdate() {
axios.get('http://localhost:8082/todos/')
.then(res => {
this.setState({ todos: res.data })
})
.catch(function (error) {
console.log(error);
});
}
todoList() {
return this.state.todos.map(function (currentTodo, i) {
return (
<Todo
todo={currentTodo}
key={i} />
);
});
};
render() {
return (
<div>
<h3>Todos List</h3>
<table className="table table-hover" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>Description</th>
<th>Responsible</th>
<th>Priority</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.todoList()}
</tbody>
</table>
</div>
)
}
}发布于 2021-09-10 03:53:02
您定义并绑定了deleteTodo,但在调用<Todo时并没有将它作为来自父级的支持传递。这是:
todoList(){
return this.state.todos.map(function (currentTodo,i){
return (
<Todo
todo={ currentTodo }
key={ i } />
);
});
};应该是
todoList(){
return this.state.todos.map((currentTodo, i) => (
<Todo
todo={currentTodo}
key={i}
deleteTodo={this.deleteTodo} />
));
};您也可以删除行。
this.deleteTodo = this.deleteTodo.bind(this);完全如此,因为您使用的是带有箭头函数的类字段。
https://stackoverflow.com/questions/69127043
复制相似问题