如何修复无法读取未定义的属性“删除”

时间:2019-04-18 17:25:47

标签: node.js reactjs mongodb express axios

我正在学习创建完整的应用程序,但是我有从数据库后端请求工作中删除记录的问题,但是,我无法添加将触发删除的按钮

const Todo = props => (
<tr>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_description}</td>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_responsible}</td>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_priority}</td>
    <td className="TableTitle">
        <Link to={"/edit/"+props.todo._id}  className="a_edit"><img src={edit} alt="Edytuj" className="favicon"/></Link>
        <button onSubmit={this.delete}>Usunięcie</button>
    </td>
</tr>

constructor(props) {
    super(props);
    this.delete = this.delete.bind(this);
    this.state = {todos: []};
}

delete(){
    axios.get('http://localhost:4000/todos/delete'+this.props.obj._id)
    .then(console.log('Deleted'))
    .catch(err =>console.log(err))
}

有一种删除方法:

constructor(props) {
    super(props);
    this.OnRemoveTodo = this.OnRemoveTodo.bind(this);
    this.state = {todos: []};
}
OnRemoveTodo(){
    axios.get('http://localhost:4000/todos/delete'+this.todo._id)
    .then(console.log('Deleted'))
    .catch(err =>console.log(err))
}

已更改const Todo:

const Todo = props => (
<tr>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_description}</td>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_responsible}</td>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_priority}</td>
    <td className="TableTitle">
        <Link to={"/edit/"+props.todo._id}  className="a_edit"><img src={edit} alt="Edytuj" className="favicon"/></Link>
        <button onSubmit={props.OnRemoveTodo}><img src={trash} alt="Usuń" className="favicon"/></button>
    </td>
</tr>

这是我要吸引的后端代码

todoRoutes.route('/delete/:id').get(function (req, res) {
Todo.findByIdAndDelete(req.params.id, function(err, todo) {
    if(err) res.json(err);
    else res.json('Successfully removed');
});

});

1 个答案:

答案 0 :(得分:1)

没有this.delete方法。 您正在使用功能组件。 我忘了使用props.delete

const Todo = props => (
<tr>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_description}</td>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_responsible}</td>
    <td className={props.todo.todo_completed ? 'completed' : 'TableText'}>{props.todo.todo_priority}</td>
    <td className="TableTitle">
        <Link to={"/edit/"+props.todo._id}  className="a_edit"><img src={edit} alt="Edytuj" className="favicon"/></Link>
        <button onSubmit={props.delete}>Usunięcie</button>
    </td>
</tr>