【问题标题】:Calling React setState from inside a child function从子函数内部调用 React setState
【发布时间】:2016-03-10 20:50:44
【问题描述】:

我有一个 React 组件,它有一个在其中一个函数中调用 Meteor 登录方法的函数。如果登录成功,我需要调整组件状态,但这是失败的。我猜我需要另一个绑定(这个)或某处的东西,但不确定在哪里。或者也许我需要将 setState 提取到另一个函数中并从这个函数中调用它。解决此类问题的典型/最佳方法是什么?

-SomeComponent.jsx

handleSubmitLogin(e) {
  e.preventDefault();
  let email="my@email.com";
  let password='mypassword';
  Meteor.loginWithPassword(email, password, function(error) {
    if (Meteor.user()) {
      this.setState({  //<- ***THIS ERRORS WITH 'Cannot read property setState of undefined'***
        showLogin: false,
      });
    } else {
      console.log("There was an error logging in: "
        + error.reason);
    }
  })
}

TIA!

【问题讨论】:

  • 在回调函数上使用.bind(this)Meteor.loginWithPassword(email, password, function (error) {}.bind(this));
  • 另外,看起来你正在使用 ES6,所以你可以只使用箭头函数:Meteor.loginWithPassword(email, password, (error) =&gt; { ... });。箭头函数从其周围范围继承 this
  • 两者都有效,并感谢您快速而有帮助的回复。由于我们正在慢慢迁移到 ES6,我们将使用第二个。如果你们中的某个人想将您的回复作为答案发布,我会接受,以便您获得代表。

标签: meteor reactjs meteor-accounts


【解决方案1】:

看起来你使用的是 ES6,所以你可以使用箭头函数:

Meteor.loginWithPassword(email, password, (error) =&gt; { ... });

箭头函数有效地从其周围范围继承this,因此this 将引用您函数中的正确内容。

如果你卡在 ES5 上,你可以简单地绑定 this 上下文:

Meteor.loginWithPassword(email, password, function (error) { ... }.bind(this));

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 2017-07-11
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2017-03-05
    • 2020-11-15
    相关资源
    最近更新 更多