首页 > 解决方案 > 状态未定义 no-undef ReactJS?

问题描述

所以我不断收到错误Line 29: 'answers' is not defined no-undef,我不太确定发生了什么或如何修复它(我对 React 和 JS 很陌生)。谁能解释这意味着什么并给我一些指示?谢谢!

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

更新:这是新addQuestion功能的样子

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

单击此按钮时我调用此函数<button onClick={this.addQuestion}>Add Question</button>

现在我收到此错误TypeError: Cannot read property 'setState' of undefined

标签: javascriptreactjs

解决方案


我想也许你的意思是这样写,它将this使用箭头函数绑定到函数:

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

或者

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

您编写它的方式answers是未定义的,并且() => {this.state.answers.concat("hello")}是对setState


推荐阅读