javascript - 反应中的动作后刷新表
问题描述
嗨,我试图制作一个 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;
这是我在这里尝试的,我的删除和我的更新工作,但只有在我刷新页面时才确认修改。
解决方案
看起来您只有来自组件中 API的get
业务数据。componentDidMount
Index
componentDidMount
相反,您应该有一个从 API 获取数据并在 TableRow.then
中的方法中调用它的方法。delete
例如:
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,以便它可以访问它。
推荐阅读
- scala - Spark get all rows with same values in array in column
- javascript - 如何使用打字稿键入此回调函数
- python - 谷歌云功能上的sshtunnel转发和mysql连接
- ruby - 登录网站并下载文件 - ruby
- javascript - 您如何摆脱警报框并恢复行动流程?- Javascript
- typescript - Jest 无法导入包,而我的其他打字稿代码导入它
- javascript - 打字稿:有条件地将对象属性标记为可选?
- java - 如何用 Jackson 序列化扩展 TreeSet 的类?
- mysql - 使用单个查询获取列中每个值的顶级类别
- r - 复制蒙蒂大厅游戏