我对 setState 有一些问题,并收到一条消息:无法读取 null 的属性"setState"



请帮助。在我的代码中有些错误,但我无法理解到底是什么,可能是语法错误,但我在这里找不到:

import React, { Component } from 'react';
class Note extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: false
    }
  }
  edit() {
    **this.setState({ editing: true })** // probaly problem here
  }
  save() {
    this.setState({ editing: false }) // here
  }
  remove() {
    alert("Removing Note") //and here
  }
  renderForm() {
    return (
      <div className="note">
        <textarea></textarea>
        <button onClick={ this.save }></button>
      </div>
    )
  }
  renderDisplay() {
    return (
      <div className="note">
        <p>{ this.props.children }</p>
        <span>
          <button onClick={ this.edit }>EDIT</button>
          <button onClick={ this.remove }>X</button>
        </span>
      </div>
    )
  }
  render() {
    if( this.state.editing ) {
      return this.renderForm()
    } else {
      return this.renderDisplay()
    }
  }
}
export default Note;

Chrome的消息是:" 无法读取null 的属性'setState'在线BOLD this.setState({ editing: true })上,我单击"编辑"按钮后,

您的方法需要绑定到类。

constructor(props) {
  super(props);
  this.state = {
    editing: false
  }
  this.edit = this.edit.bind(this);
  this.save = this.save.bind(this);
}

还有一个实验/提案功能,使您可以通过使用箭头函数作为类方法来绑定这些绑定而无需明确绑定。这个问题有更多信息。

相关内容

最新更新