我想把它转换成一个useEffect
钩子:
代码
componentDidMount () {
this.messagesRef.on('child_added', snapshot => {
const message = snapshot.val();
message.key = snapshot.key;
this.setState({messages: this.state.messages.concat(message
)});
});
更新代码
const MessageList = () => {
const [messages, setMessage] = useState([]);
const [usernames, setUsernames] = useState('');
const [contents, setContents] = useState('');
const [roomId, setRoomId] = useState('');
const messagesRef = MessageList.props.firebase.database().ref('messages');
useEffect(() => {
messagesRef.on('child added', snapshot => {
const message = snapshot.val();
message.key = snapshot.key;
const [messages, setMessages] = useState({messages: messages.concat(message)});
});
})
}
现在它给了我一个useState cannot be used in a callback
.
我该如何解决这个问题或正确转换它?