简体   繁体   English

this.setState不是一个函数,为什么它不起作用?

[英]this.setState is not a function why it didn't work?

Hi i'm not verry good using react and i don't understand why my this.setState dont work here but on some other files it is. 嗨,我不是很好用反应,我不明白为什么我的this.setState不在这里工作,但在其他一些文件。 On my other files it is written exactly the same and it works but not here. 在我的其他文件上,它写的完全相同,但它可以工作但不在这里。 Can someone tell me why ? 有人可以告诉我为什么吗?

test(event){
event.preventDefault();
var regex_mongoinclude = document.getElementById("regexinclude").value;
var regex_mongoexclude = document.getElementById("regexexclude").value;
if (this.props.item.type == "email") {
  (function(prop) {
    var text = document.getElementById("name_sub").value;
    var reg = /^([a-zA-Z0-9.\-_]+[@]{1}[a-zA-Z0-9\-_]+[.]{1}[a-zA-Z0-9\-_]+[,]*)+/;
    if(reg.test(text)==true) {
      Subs.update(
        { _id: prop.item._id },
        {
          text,
          type :"email",
          createdAt: new Date(),
          regex_mongoinclude,
          regex_mongoexclude,
          topic:prop.parent._id,

        },
        { upsert: true }
      )
      this.setState({
        showMessage: true,
        isError: false
      });
    } else {
      this.setState({
        showMessage: true,
        isError: true
      });
    }
  })(this.props)
} else if (this.props.item.type == "slack") {

In this line: 在这一行:

(function(prop) {

You're creating a new closure, essentially losing the reference to the correct this object. 你正在创建一个新的闭包,基本上失去了对正确的this对象的引用。 You could replace it with: 您可以将其替换为:

((prop) => {

The arrow function keeps the correct closure intact. 箭头功能保持正确的闭包完好无损。 But honestly, I'm not sure why you even need it in this case, you could put your code directly in the if statement and wouldn't need to create an IIFE. 但说实话,我不确定为什么在这种情况下你甚至需要它,你可以将你的代码直接放在if语句中,而不需要创建一个IIFE。

'test' function seems to be an event handler. 'test'函数似乎是一个事件处理程序。 this inside an event handler has to be binded manually in the component contructor with something like: this事件处理程序内部必须在组件构造器中手动绑定,例如:

// inside constructor
this.test = this.test.bind(this)

After that this.setState will work hopefully. 之后, this.setState将有希望地工作。

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

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