我的ReactJS应用程序中有一个函数,该函数向服务器发送axios POST请求以从数据库中删除某个元素。
基本上,我有一个列表,可以从中删除某些项目,但是,React仅显示刷新页面后通过删除元素所做的更改。
这是我使用的删除功能:
handleDelete (event) { var id = event.target.id; axios.get('todos/delete?id='+id) .then(function(response) { }); this.componentDidMount(); }
componentDidMount()从我的数据库中获取数据并将其存储在状态中。我发现,如果我componentDidMount在该函数中调用,它将立即显示更改,但是,我觉得这是一种非常不专业的方式来完成我要实现的目标。因此,我的问题是:
componentDidMount()
componentDidMount
好吧,你不应该真的那样做。
componentDidMount 只是 组件 的生命周期方法。您想要的是这种结构:
fetchData () { ... }; handleDelete (event) { var id = event.target.id; axios.get('todos/delete?id='+id) .then(function(response) { }); this.fetchData(); } componentDidMount() { this.fetchData(); }
这是一个简化的示例,但您明白了。
注意: 在 handleDelete 函数中,如果您希望 fetchData 调用在 axios 调用 之后 发生 , 则应在代码中进行编码, 然后
axios.get('todos/delete?id='+id) .then(() => { this.fetchData(); });