簡體   English   中英

沒有定義狀態否undef ReactJS?

[英]State is not defined 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

我想也許你的意思是把它寫像這樣,將結合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的回調

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM