【问题标题】:How to setState inside an api function如何在 api 函数中设置状态
【发布时间】:2021-02-08 01:40:21
【问题描述】:

我在类方法中有这段代码:

ref
      .orderByValue()
      .equalTo(email)
      .once("value", snapshot => {
        if (snapshot.exists()) {
          console.log(this);
          this.setState({ signedUp: true });
        } else {
          ref.update({ [newKey]: email });
        }
      });

它将在提交时更新我的​​ Firebase 数据库,除非用户已经注册。 typeError 表示this.setState is not a function。但是当我控制台登录this 时,控制台会打印出课程。记录 this.state 也会打印出状态。

我该如何解决这个问题?我想从这个函数内部更新我的状态。

【问题讨论】:

  • 添加类的完整代码

标签: reactjs firebase react-class-based-component


【解决方案1】:

最好的解决方案是使用函数式组件。

但是如果你想使用类组件,这可能是一个绑定问题。

因此,如果这是在名为 func 的函数内部触发的,则应将此函数绑定到构造函数中。

...
constructor(props) {
...
this.func = this.func.bind(this);
...
}
func() {
...
ref
      .orderByValue()
      .equalTo(email)
      .once("value", snapshot => {
        if (snapshot.exists()) {
          console.log(this);
          this.setState({ signedUp: true });
        } else {
          ref.update({ [newKey]: email });
        }
      });
...
}

如果你不想绑定这个函数,你应该使用箭头函数。

func = () => {
...
}

【讨论】:

  • self=此解决方法适用于 es5。它对箭头没有帮助。
猜你喜欢
  • 2021-02-12
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 2021-12-18
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
相关资源
最近更新 更多