【发布时间】:2021-01-24 00:59:15
【问题描述】:
删除后不会从表中删除该行。 单击操作后,它会正确更新数据库、数组和状态,但不会呈现我的视图,因为我仍然看到该行。 一旦我离开页面并返回,记录就消失了;但是,这是有道理的,因为数据库是通过发布请求更新的。 我已经安慰了数组和状态,删除后都在更新。
import React,{ PureComponent } from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
class Listing extends PureComponent{
state = {
categories: []
};
componentDidMount(){
axios.get('http://127.0.0.1:8000/category')
.then(response=>{
this.setState({categories:response.data});
});
}
deleteCategory = (e)=>{
axios.delete('http://127.0.0.1:8000/category/delete/'+e)
.then(response=> {
var array = this.state.categories;
for(var i = 0 ; i < array.length ; i++){
if(array[i].id == e){
array.splice(i,1);
this.setState({categories:array});
}
}
});
}
render() {
return(
<div>
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Category Name</th>
<th scope="col">Status</th>
<th scope="col">Created At</th>
<th scope="col">Updated At</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{
this.state.categories.map(category=>{
return(
<tr>
<th scope="row">{category.id}</th>
<td>{category.name}</td>
<td>{category.active == 1 ? ("Active"): ("InActives")}</td>
<td>{category.created_at}</td>
<td>{category.updated_at}</td>
<td><button className="btn btn-danger" onClick={(e)=>this.deleteCategory(category.id)}>Delete</button> </td>
</tr>
)
})
}
</tbody>
</table>
</div>
);
}
}
export default Listing;
【问题讨论】: