2017-04-05 51 views
0

我打电话从一个子组件此功能:反应,未定义,则此

removeWorkout: function (workoutId) { 
return axios.delete('/delete', { 
     params: { 
      id: workoutId 
     } 
     } 
    .then(function(response){ 
     this.componentDidMount(); 
    }); 
}, 

服务器删除一条记录:

app.delete('/delete/:id?', (req, res) => { 
    Exr.find({'_id':req.query.id}).remove().exec(); 
    console.log("server deleting") 
    res.send("done") 
}); 

this.componentDidMount不起作用,因为这是不确定的。其他功能工作。

+1

尝试'.then((response)=> {this.componentDidMount();})' –

回答

3

它是一个绑定问题,你需要绑定context通过使用.bind(this)或使用arrow function,arrow function将为你做这个工作。

使用此:

.then((response) => { 
     this.componentDidMount(); 
}); 

.then(function(response) { 
     this.componentDidMount(); 
}.bind(this)); 
+0

谢谢!这解决了它! –

0

这是不工作的原因是因为this被反弹到你的回调函数:

removeWorkout: function (workoutId) { 
return axios.delete('/delete', { 
     params: { 
      id: workoutId 
     } 
     } 
    .then(function(response){ 
     // "this" now refers to your function(response){...} callback 
     this.componentDidMount(); 
    }); 
}, 

您解决办法这个问题是使用arrow function,它保留了父母的范围(this将把你的阵营组件):

removeWorkout: function (workoutId) { 
return axios.delete('/delete', { 
     params: { 
      id: workoutId 
     } 
     } 
    .then((response) => { 
     this.componentDidMount(); 
    }); 
}, 

或通过捕捉this到一个变量在进入回调:

removeWorkout: function (workoutId) { 
var _this = this; 
return axios.delete('/delete', { 
     params: { 
      id: workoutId 
     } 
     } 
    .then(function(response){ 
     _this.componentDidMount(); 
    }); 
}, 

作为一个侧面说明,你真的不应该是手动触发生命周期方法,最好调用setState这将触发组件更新。

+0

谢谢,我认为这将是更好使用setState,但我有错误,当我试着this.setState(this.state) –

0

您的问题是,JavaScript中的this是一个魔术关键字,它指向调用方法的对象。如果方法未在您期望的对象上调用,这可能会导致很多问题。有关this如何在JavaScript中工作的一些深入内容here

你可以通过明确绑定你的函数来解决这个问题,这样this总是指向它中的同一个对象。 。要做到这一点,你可以使用[Function.bind(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)如果你的功能被命名为“功能”,可以这样做:

constructor(props) { 
    super(props); 
    this.function = this.function.bind(this); 
} 

然而,在这种情况下,你使用componentDidMount,这是部分的React组件生命周期,所以你可能不应该绑定它。另一种方法是使用一个箭头的功能,如箭头函数总是有一个静态绑定this

removeWorkout: (workoutId) => { 
return axios.delete('/delete', { 
     params: { 
      id: workoutId 
     } 
     } 
    .then(response => 
     this.componentDidMount()); 
)} 

顺便说一句,直接调用componentDidMount()通常是一个不好的做法。您不应该直接调用React生命周期方法。相反,你应该提取你想调用的函数,并在这个方法和方法中调用它。

+0

谢谢!这也可以! –