我一直试图删除todo时,删除按钮被点击,但浏览器抛出一个运行时错误说:"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>
)
}
}
错误图像
您定义并绑定了deleteTodo
,但在调用<Todo
时没有将其作为父级的prop传递下去。:
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);
,因为您使用的是带有箭头函数的类字段。