无法在 React 回调中访问 'this' 函数
can't access 'this' function in React callback
我有一个 React 组件,我需要在成功调用数据库后更改状态。数据库调用使用了一个我无法更改的回调函数,但是我无法从回调函数中找到在同一组件中访问重定向函数的方法。我刚收到错误 enableRedirect' of null
我试过将回调函数更改为箭头函数,但无法正确调用。我一直在阅读类似问题的其他答案,但无法使其适用于我的情况
...
componentDidUpdate = (prevProps, prevState) => {
if (prevState.braintreeToken !== this.state.braintreeToken) {
dropin.create(
{
authorization: this.state.braintreeToken,
container: "#dropin-container",
},
//callback function happens here
(createErr, instance) => {
button.addEventListener("click", function() {
instance.requestPaymentMethod(function(
requestPaymentMethodErr,
payload
) {
api
.submitPayload(payload, plan, id)
.then(res => {
//this is where I'm trying to call my enable redirect function
this.enableRedirect();
})
.catch(err => {
//error handling
});
});
});
}
);
}
};
// the function I'm trying to call
enableRedirect = () => {
this.setState({
redirect: true
});
};
...
我需要在回调中调用 enableRedirect 函数!
而不是这个
button.addEventListener("click", function() {
});
使用
button.addEventListener("click", () => {
});
箭头函数和普通函数的这个值不同。对于普通功能,此 将是您单击的按钮。
参考这个link。
我有一个 React 组件,我需要在成功调用数据库后更改状态。数据库调用使用了一个我无法更改的回调函数,但是我无法从回调函数中找到在同一组件中访问重定向函数的方法。我刚收到错误 enableRedirect' of null
我试过将回调函数更改为箭头函数,但无法正确调用。我一直在阅读类似问题的其他答案,但无法使其适用于我的情况
...
componentDidUpdate = (prevProps, prevState) => {
if (prevState.braintreeToken !== this.state.braintreeToken) {
dropin.create(
{
authorization: this.state.braintreeToken,
container: "#dropin-container",
},
//callback function happens here
(createErr, instance) => {
button.addEventListener("click", function() {
instance.requestPaymentMethod(function(
requestPaymentMethodErr,
payload
) {
api
.submitPayload(payload, plan, id)
.then(res => {
//this is where I'm trying to call my enable redirect function
this.enableRedirect();
})
.catch(err => {
//error handling
});
});
});
}
);
}
};
// the function I'm trying to call
enableRedirect = () => {
this.setState({
redirect: true
});
};
...
我需要在回调中调用 enableRedirect 函数!
而不是这个
button.addEventListener("click", function() {
});
使用
button.addEventListener("click", () => {
});
箭头函数和普通函数的这个值不同。对于普通功能,此 将是您单击的按钮。
参考这个link。