繁体   English   中英

如何在 api function 中设置状态

[英]How to setState inside an api function

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

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时,控制台打印出 class。记录this.state也打印出 state。

我该如何解决? 我想从这个 function 中更新我的 state。

最好的解决方案是使用功能组件。

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

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

...
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 });
        }
      });
...
}

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

func = () => {
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM