[英]React, undefined this
我从子组件调用此函数:
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
不起作用,因为这是未定义的。 其他功能起作用。
它是一个绑定问题,你需要使用.bind(this)
绑定context
或使用arrow function
, arrow function
将为你完成这项工作。
用这个:
.then( (response) => {
this.componentDidMount();
});
要么
.then( function(response) {
this.componentDidMount();
}.bind(this));
这不起作用的原因是因为this
会反弹到你的回调函数:
removeWorkout: function (workoutId) {
return axios.delete('/delete', {
params: {
id: workoutId
}
}
.then(function(response){
// "this" now refers to your function(response){...} callback
this.componentDidMount();
});
},
解决此问题的方法是使用箭头函数 ,该函数保留父级的范围( this
将引用您的React组件):
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
来触发组件更新。
您的问题是JavaScript中的this
是一个神奇的关键字,它指的是调用方法的对象。 当没有在您期望的对象上调用方法时,这可能会导致很多问题。 有一个关于如何一些深层次的内容this
工程在JavaScript 这里 。
您可以通过显式绑定您的函数,以便绕开这个问题this
通常是指在它同一个对象。 为此,使用[Function.bind]。( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind )如果您的函数名为“function”,你可以做:
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生命周期方法。 相反,您应该提取要调用的函数,并在此方法和componentDidMount
方法中调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.