删除后不会将其从表中删除。 单击操作后,它会正确更新数据库,数组和状态,但不会呈现我的视图,因为我仍然看到该行。 一旦我离开页面返回,记录就消失了。但是,这是有道理的,因为数据库是通过发布请求来更新的。 我已经控制了阵列以及状态,两者都在删除后更新。
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;
答案 0 :(得分:0)
状态不能在React中改变。如果需要从数组中删除项目,并且要使用splice
,则应首先复制数组,例如:
const categoriesCopy = [...this.state.categories];
但是在splice
循环中使用for
也会导致某些数组元素被跳过,因为您要在迭代数组时对其进行突变。
改为使用.filter
:
const { categories } = this.state;
this.setState({
categories: categories.filter(cat => cat.id !== e)
});