因此,我在React中为我的Crud应用程序创建了一个delete方法。我的删除方法有效,但是为了使数据消失,我总是必须刷新页面。我可以采取哪些方法解决此问题。以下是我的删除方法代码
import React, {Component} from 'react';
import './App.css';
import axios from 'axios';
import { Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
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>{this.props.object.marks}</td>
<td> <Link to ={"/editform/"+ this.props.object._id} className = 'btn-btn-danger'>Update</Link> </td>
<td> <button onClick={this.deletestudent} className = 'btn-btn-danger'>Remove</button></td>
</tr>
);
}
}
答案 0 :(得分:0)
我想你有一些可以保留学生名单的东西。在以下代码示例中,我将其命名为Table
。它加载数据并处理单个项目的删除。如果您编辑数据,则还可以将其处理程序添加到Table
中,以便所有内容保持同步。
import React, {Component, useState} from 'react';
import './App.css';
import axios from 'axios';
import { Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
function Table() {
const [students, updateStudents] = useState([])
useEffect(() => {
axios.get('http://localhost:3200/students')
.then((response) => response.JSON())
.then((studentsResp) => updateStudents(studentsResp))
}, []);
const onRemoveStudent = useCallback((student) => {
axios.post('http://localhost:3200/students/deleteStudent', {
'_id': student._id
})
.then(console.log('Student Deleted'))
.then(() => {
let newStudentsArr = students;
const index = newStudentsArr.findIndex((obj) => obj._id === student._id);
newStudentsArr.splice(index, 1);
})
.catch(err => console.log(err));
}, []);
return <table>
{students.map((student, index) => {
<TableRow key={index} object={student} onRemove={onRemoveStudent} />
})}
</table>
}
export default class TableRow extends Component {
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>{this.props.object.marks}</td>
<td> <Link to ={"/editform/"+ this.props.object._id} className = 'btn-btn-danger'>Update</Link> </td>
<td> <button onClick={() => this.props.onRemove(this.props.object)} className = 'btn-btn-danger'>Remove</button></td>
</tr>
);
}
}
用法:
import React from 'react';
import ReactDOM from 'react-dom';
import Table from './components/Table';
const App = () => {
return <div>
<h2>Your App</h2>
{/* other code from yours */}
<Table />
</div>
}
const root = document.getElementById('root');
ReactDOM.render(<App />, root);
答案 1 :(得分:0)
您从哪里获得学生名单?解决此问题的一种简单方法是,在delete函数的.then()内部,再次调用学生列表
请记住:每次更改状态时,页面都会重新渲染,因此render()中的所有内容都会再次执行。帮忙使用