0
我打算從我的React組件中的Firebase獲取快照val。我想獲取基於組件init的值並附加一個偵聽器以進行更改。React - 無法獲取屬性setState null
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>
);
}
}
忘記了箭頭功能的力量!這是做的伎倆,謝謝! – Yasir