我无法访问状态或setState

时间:2018-08-16 07:10:38

标签: javascript reactjs

我想从state.messages方法更新readFromFile数组,这给了我无法读取未定义的属性'setState'错误。但是我在该方法中登录了this,在那里我可以看到state。我想念什么?

此外,我想从this.state.messages方法向readFromFile添加对象(当我从API返回响应时)。我怎样才能做到这一点?

我正在寻找一个解决方案,我发现的唯一问题是绑定问题(我确实这样做了)

class Main extends Component {

  constructor() {
    super();
    this.readFromFile = this.readFromFile.bind(this);
    // this.readFromFile = this.readFromFile.bind(this);
  }

  state = {
    count: 0,
    messages: [{type: 'sent', content: "test1"}, {type: 'received', content: "test2"}],
    inputText: ''
  };

  render() {
    return(
      <React.Fragment>
        <span>{ this.renderMessage() }</span>
        <input type="text" value={this.state.inputText} onChange={this.handleTextInput} />
        <button onClick={this.handleSendClick}>Send</button>
      </React.Fragment>
    );
  }

  handleTextInput = (event) => {
    this.setState({inputText: event.target.value});
  }

  handleSendClick = () => {
    console.log(this);
    if (this.state.inputText === "read") {
      this.readFromFile();
      // this log works fine
      console.log(this.state.messages);
    }

    // const { count } = this.state;
    // return count === 0 ? <h1>Zero</h1> : count;
  }

  readFromFile = () => {
    console.log(this);
    fetch('http://localhost:8000/read')
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        console.log(myJson.content);
        // update NOT WORKING
        // this.setState({messages: this.state.messages.concat({content: myJson.content, type: 'received'})})
        // this log gives TypeError: Cannot read property 'state' of undefined
        // console.log(this.state.messages);
      });
  }

  renderMessage() {
    if (this.state.messages.length === 0) return <p>No message found!</p>;
    return <ul>{this.state.messages.map((msg, idx) => <li key={idx}>{msg.content}</li>)}</ul>;
  }

}

export default Main;

0 个答案:

没有答案