[英]refresh table after action in react
嗨,我嘗試制作了MERN應用
但是有件事,當我審核或刪除頁面時沒有刷新,該怎么辦? 我創建一個索引,列出所有條目
// index.component.js
import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';
export default class Index extends Component {
constructor(props) {
super(props);
this.state = {business: []};
}
componentDidMount(){
axios.get('http://localhost:4000/business')
.then(response => {
this.setState({ business: response.data });
})
.catch(function (error) {
console.log(error);
})
}
tabRow(){
return this.state.business.map(function(object, i){
return <TableRow obj={object} key={i} />;
});
}
render() {
return (
<div>
<h3 align="center">Liste des billets</h3>
<table className="table table-striped" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>Nom Prénom</th>
<th>Poste</th>
<th>Téléphone</th>
<th colSpan="2">Action</th>
</tr>
</thead>
<tbody>
{ this.tabRow() }
</tbody>
</table>
</div>
);
}
}
這是我的桌子
// TableRow.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
class TableRow extends Component {
constructor(props) {
super(props);
this.delete = this.delete.bind(this);
}
delete() {
axios.get('http://localhost:4000/business/delete/'+this.props.obj._id)
.then(console.log('Deleted'))
.catch(err => console.log(err))
}
render() {
return (
<tr>
<td>
{this.props.obj.nomPrenom}
</td>
<td>
{this.props.obj.posteEntreprise}
</td>
<td>
{this.props.obj.numeroTel}
</td>
<td>
<Link to={"/edit/"+this.props.obj._id} className="btn btn-primary">Editer</Link>
</td>
<td>
<button onClick={this.delete} className="btn btn-danger">Supprimer</button>
</td>
</tr>
);
}
}
export default TableRow;
這是我在這里嘗試的操作,我的刪除和更新工作正常,但是只有在刷新頁面后才能確認修改。
您必須在刪除/編輯請求的回調中更新數據。
當前,您只需記錄刪除已成功。
看來您只能從Index
組件的componentDidMount
中的API get
業務數據。
相反,您應該有一個方法可以從API獲取數據,並在componentDidMount
和TableRow中delete
方法的.then
中調用它。
例如:
componentDidMount(){
this.getBusinessData();
}
getBusinessData() {
axios.get('http://localhost:4000/business')
.then(response => {
this.setState({ business: response.data });
})
.catch(function (error) {
console.log(error);
})
}
tabRow(){
return this.state.business.map(function(object, i){
return <TableRow obj={object} getBusinessData={this.getBusinessData} key={i} />;
});
}
在TableRow中:
delete() {
axios.get('http://localhost:4000/business/delete/'+this.props.obj._id)
.then(() => {
console.log('Deleted'));
this.props.getBusinessData();
})
.catch(err => console.log(err))
}
請注意,您還必須將方法作為道具傳遞給TableRow,以便它可以訪問它。
在刪除功能中,您應該更新狀態
delete() {
axios.get('http://localhost:4000/business/delete/'+this.props.obj._id)
.then(()=>{
let list=this.state.business.filter((item)=>return (item.id===this.props.obj._id))
this.setState({business:list})}
.catch(err => console.log(err))
}
idk如何在您的情況下刪除,因為我不知道列表,但應該類似
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.