从子函数内部调用 React setState

Calling React setState from inside a child function

我有一个 React 组件,它有一个函数可以在其中一个函数中调用 Meteor 登录方法。如果登录成功,我需要调整组件状态,但那是失败的。我猜我需要另一个 bind(this) 或某处的东西,但不确定在哪里。或者我可能需要将 setState 提取到另一个函数中并从这个函数中调用它。 typical/best 处理此类问题的方法是什么?

-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!

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

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

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

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

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