在函数中调用 componentDidMount 是不好的做法吗? [英] Is calling componentDidMount within a function bad practice?
问题描述
我的 ReactJS 应用中有一个函数可以向服务器发送 axios POST 请求以从我的数据库中删除某个元素.
I have a function in my ReactJS app that sends an axios POST request to the server to delete a certain element from my database.
基本上,我有一个列表,我可以从中删除某些项目,但是,React 仅显示刷新页面后删除元素所做的更改.
Basically, I have a list and I can delete certain items from it, however, React only displays the changes made by deleting an element after refreshing the page.
这是我使用的删除函数:
Here is the delete function that I use:
handleDelete (event) {
var id = event.target.id;
axios.get('todos/delete?id='+id)
.then(function(response) {
});
this.componentDidMount();
}
componentDidMount()
从我的数据库中获取数据并将其存储在状态中.我发现,如果我在函数中调用 componentDidMount
,它会立即显示更改,但是,我觉得这是一种相当不专业的方式来完成我想要实现的目标.因此,我的问题是:
componentDidMount()
fetches data from my database and stores it in the state.
I found that, if I call componentDidMount
within the function, that it displays the changes right away, however, I kind of feel like that's a rather unprofessional way of doing what I'm trying to achieve.
Therefore my questions are:
- 在另一个函数中调用生命周期方法是否被认为是不好的做法?
- 是否有更好的方法让页面立即显示更改?
推荐答案
其实你不应该那样做.
componentDidMount 只是一个生命周期方法你的组件.你想要的是这个结构:
componentDidMount is just a lifecycle method of your component. What you want is this structure:
fetchData () { ... };
handleDelete (event) {
var id = event.target.id;
axios.get('todos/delete?id='+id)
.then(function(response) {
});
this.fetchData();
}
componentDidMount() {
this.fetchData();
}
这是一个简化的例子,但你明白了.
This is a simplified example but you get the point.
注意:在 handleDelete 函数中,如果您希望 fetchData 调用在 axios 调用您的之后发生应该只是 then
NOTE: in the handleDelete function if you want the fetchData call to happen after the axios call your should but the code inside the then
axios.get('todos/delete?id='+id)
.then(() => {
this.fetchData();
});
这篇关于在函数中调用 componentDidMount 是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!