简体   繁体   English

没有定义状态否undef ReactJS?

[英]State is not defined no-undef ReactJS?

So I keep getting the error Line 29: 'answers' is not defined no-undef and I am not quite sure what's going on or how to fix it (I'm very new to React and JS). 因此,我不断收到错误Line 29: 'answers' is not defined no-undef而且我不确定所发生的事情或如何解决(我对React和JS来说是新手)。 Could anyone perhaps explain what this means and give me a few pointers? 谁能解释这意味着什么,并给我一些指导? Thanks! 谢谢!

class App extends Component {


  constructor(props){
    super(props);
      this.state = {
        key: myUUID,
        title: "",
        author: "",
        questions: [],
        answers: []
      }
  }

  addQuestion(){
    questionNum++;
    this.setState({
      answers }, () => {
      this.state.answers.concat("hello")
    });
  }

UPDATE: Here's what the new addQuestion function looks like 更新:这是新的addQuestion函数的外观

  addQuestion(){
    questionNum++;
    this.setState({
      answers: this.state.answers.concat("hello")
    });
  }

I call this function when this button is clicked <button onClick={this.addQuestion}>Add Question</button> 单击此按钮时,我会调用此函数<button onClick={this.addQuestion}>Add Question</button>

Now I am getting this error TypeError: Cannot read property 'setState' of undefined 现在我收到此错误TypeError: Cannot read property 'setState' of undefined

I think perhaps you mean to write it like this, which will bind this to the function with the arrow function: 我想也许你的意思是把它写像这样,将结合this与箭头函数的函数:

addQuestion = () => {
  questionNum++;
  this.setState({
    answers: this.state.answers.concat("hello")
  });
}

or 要么

const answers = this.state.answers.concat("hello");
this.setState({ answers });

The way you have it written, answers is undefined, and () => {this.state.answers.concat("hello")} is a callback to setState 您编写它的方式, answers是不确定的,并且() => {this.state.answers.concat("hello")}是对setState的回调

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

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