所以我试图在前端UI上的React中做一个delete方法,我收到200 ok请求,但是我可能做错了,所以这是我的前端和后端代码以及Ui的屏幕截图>
front end
import React, {Component} from 'react';
import './App.css';
import axios from 'axios';
export default class TableRow extends Component {
constructor(props) {
super(props);
this.deletestudent = this.deletestudent.bind(this);
}
deletestudent(student_id) {
axios.post('http://localhost:3200/students/deleteStudent')
.then(console.log('Student Deleted'))
.catch(err => console.log(err));
}
render(){
return(
<tr>
<td>{this.props.object._id}</td>
<td>{this.props.object.role_num} </td>
<td>{this.props.object.first_name}</td>
<td>{this.props.object.last_name}</td>
<td><button className = 'btn-btn-danger'>Update</button> </td>
<td><button onClick={this.deletestudent} className = 'btn-btn-danger' color='blue'> Remove</button></td>
</tr>
);
}
}
后端
second.post('/students/deleteStudent', (req, res) => {
res.send('delete student'+req.body._id);
try {
db.collection('students').deleteOne( { "_id" : ObjectID(req.body._id) } );
} catch (e) {
console.log(e);
}
res.send('delete student');
});
当我单击响应时,我得到未定义的删除学生,是否需要更改后端,我知道我需要按ID进行删除,但无法弄清楚
答案 0 :(得分:0)
这里需要两次更正。
_.id
作为student_id
传递给deletestudent
函数或从道具中使用。student_id
。代码
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
export default class TableRow extends Component {
constructor(props) {
super(props);
this.deletestudent = this.deletestudent.bind(this);
}
deletestudent() {
axios.post('http://localhost:3200/students/deleteStudent', {
'_id': this.props.object._id
})
.then(console.log('Student Deleted'))
.catch(err => console.log(err));
}
render() {
return (
<tr>
<td>{this.props.object._id}</td>
<td>{this.props.object.role_num} </td>
<td>{this.props.object.first_name}</td>
<td>{this.props.object.last_name}</td>
<td><button className='btn-btn-danger'>Update</button> </td>
<td><button onClick={this.deletestudent} className='btn-btn-danger' color='blue'> Remove</button></td>
</tr>
);
}
}