2017-04-05 58 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

謝謝!這也可以! –

相關問題