Reactjs 无法访问React回调中的“this”函数
我有一个React组件,在成功调用数据库后,我需要在其中更改状态。数据库调用使用回调函数,我无法更改,但是我无法找到从回调函数中访问同一组件中重定向函数的方法。我刚刚得到了null的错误enableRedirect 我已经尝试将回调函数更改为箭头函数,但是没有正确调用它。我一直在阅读类似问题的其他答案,但无法使其适用于我的情况Reactjs 无法访问React回调中的“this”函数,reactjs,callback,this,braintree,Reactjs,Callback,This,Braintree,我有一个React组件,在成功调用数据库后,我需要在其中更改状态。数据库调用使用回调函数,我无法更改,但是我无法找到从回调函数中访问同一组件中重定向函数的方法。我刚刚得到了null的错误enableRedirect 我已经尝试将回调函数更改为箭头函数,但是没有正确调用它。我一直在阅读类似问题的其他答案,但无法使其适用于我的情况 ... componentDidUpdate = (prevProps, prevState) => { if (prevState.bra
...
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", () => {
});