【问题标题】:can't access 'this' function in React callback无法在 React 回调中访问“this”函数
【发布时间】:2019-06-19 08:22:41
【问题描述】:

我有一个 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 函数!

【问题讨论】:

    标签: reactjs callback this braintree


    【解决方案1】:

    不是这个

    button.addEventListener("click", function() {
    
    });
    

    使用

    button.addEventListener("click", () => {
    
    });
    

    箭头函数和普通函数的 this 值不同。对于普通功能,this 将是您单击的按钮。

    请参阅此link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 2017-03-14
      相关资源
      最近更新 更多