在函数中调用componentDidMount是不好的做法吗?

时间:2018-01-10 12:14:04

标签: javascript reactjs

我的ReactJS应用程序中有一个函数,它向服务器发送一个axios POST请求,以从我的数据库中删除某个元素。

基本上,我有一个列表,我可以从中删除某些项目,但是,React只显示刷新页面后删除元素所做的更改。

这是我使用的删除功能:

handleDelete (event) {
    var id = event.target.id;
    axios.get('todos/delete?id='+id)
        .then(function(response) {
        });
    this.componentDidMount();
}

componentDidMount()从我的数据库中提取数据并将其存储在该状态中。 我发现,如果我在函数中调用componentDidMount,它会立即显示更改,但是,我觉得这是一种相当不专业的方式来做我想要实现的目标。 因此我的问题是:

  • 在另一个函数中调用生命周期方法被认为是不好的做法吗?
  • 是否有更好的方法让页面立即显示更改?

3 个答案:

答案 0 :(得分:3)

嗯,你不应该那样做。

componentDidMount 只是组件的生命周期方法。你想要的是这种结构:

fetchData () { ... };

handleDelete (event) {
    var id = event.target.id;
    axios.get('todos/delete?id='+id)
        .then(function(response) {
        });
    this.fetchData();
}

componentDidMount() {
  this.fetchData();
}

这是一个简化的例子,但你明白了。

注意:句柄删除功能,如果您想要 fetchData 调用 > axios调用你的应该是然后

中的代码
axios.get('todos/delete?id='+id)
     .then(() => {
       this.fetchData();
     }); 

答案 1 :(得分:0)

回答1 - 不建议在任何函数中调用生命周期方法。

回答2 - 更好的推荐方式,调用ComponentDidMount中的所有服务器功能

for more refrence check here

您可以这样做: -

  componentDidMount(){
     // do some get opration to get data from server
      getFunction();
    }
   handleDelete (event) {
        var id = event.target.id;
        axios.get('todos/delete?id='+id)
            .then(function(response) {
                // get operation here in response
            });

    }

答案 2 :(得分:0)

确实这是一种不好的做法。您可以使用React生命周期来更新状态,也可以直接使用handleDelete函数。

handleDelete = ({ target }) => {
 const { id } = target;
 axios.get('todos/delete?id=='+id')
   .then(response => { 
       const todos = this.state.todos;
       todos.splice(indexOfTheItem,1);
       this.setState({ todos });
      })