最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - State is not defined no-undef ReactJS? - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Jul 9, 2018 at 18:53 dorkycam asked Jul 9, 2018 at 18:43 dorkycamdorkycam 5295 gold badges11 silver badges26 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论