React - 无法获取null的属性setState

时间:2017-04-12 23:28:37

标签: reactjs redux setstate

我打算在我的React组件中从Firebase获取快照值。我希望根据组件的init获取值,并附加一个监听器以进行更改。

class ChatMessages extends Component {

constructor(props) {
    super(props);
    this.state = {
      messages: [],
    };
    this.getMessages = this.getMessages.bind(this);
}

getMessages(event) {
  const messagesRef = firebase.database().ref('messages');
  messagesRef.on('value', function(snapshot) {
    this.setState({ messages: snapshot.val() });
  });
}

componentDidMount() {
  this.getMessages();
}

render() {
    return (
        <div className="container">
          <ul>
            <li>Default Chat Message</li>
            { this.state.messages }
          </ul>
        </div>
    );
}

}

1 个答案:

答案 0 :(得分:1)

这是因为&#39;这个&#39;正在失去其背景。所以,&#39; this.setState&#39;未定义。你可以参考实际的&#39;这个&#39;通过一个名为&#39;的变量&#39;

class ChatMessages extends Component {

constructor(props) {
    super(props);
    this.state = {
      messages: [],
    };
    this.getMessages = this.getMessages.bind(this);
}

getMessages(event) {
  const messagesRef = firebase.database().ref('messages');
  let that = this
  messagesRef.on('value', function(snapshot) {
    // here 
    that.setState({ messages: snapshot.val() });
  });
}

componentDidMount() {
  this.getMessages();
}

render() {
    return (
        <div className="container">
          <ul>
            <li>Default Chat Message</li>
            { this.state.messages }
          </ul>
        </div>
    );
}

}

或者,如果可能,您可以使用箭头功能,它保持其上下文。

getMessages(event) {
  const messagesRef = firebase.database().ref('messages');
  // here
  messagesRef.on('value', snapshot => {
    // here 
    that.setState({ messages: snapshot.val() });
  });
}