简体   繁体   中英

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). 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(){
    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>

Now I am getting this error 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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