You cannot use hooks inside class component. Use functional components instead:
const Lobby = () => {
const [message, updateMessage] = useState('')
const [messages, updateMessages] = useState([])
useEffect(() => {
const handleNewMessage = newMessage =>
updateMessages([...messages, newMessage])
socket.on('chat.message', handleNewMessage)
return () => socket.off('chat.message', handleNewMessage)
}, [messages]);
const handleFormSubmit = event => {
event.preventDefault()
if (message.trim()) {
socket.emit('chat.message', {
userid: myId,
lobby,
username: username,
message
})
updateMessage('')
}
}
const handleInputChange = event => updateMessage(event.target.value);
const handleTesteChange = event => updateMessage(event.target.value);
const handleTesteSubmit = event => {
event.preventDefault()
if (message.trim()) {
socket.emit('chat.message', {
userid: myId,
message
})
updateMessage('')
}
}
return (
<div>
{/* Code */}
</div>
)
}
Find more information here: https://reactjs.org/docs/hooks-intro.html
If what you want is to use class components, then you can do this:
class Lobby extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
messages: []
}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.messages !== this.state.messages){
const handleNewMessage = newMessage => this.setState({messages: ([...messages, newMessage])})
socket.on('chat.message', handleNewMessage)
return () => socket.off('chat.message', handleNewMessage)
}
}
handleFormSubmit = event => {
event.preventDefault()
if (message.trim()) {
socket.emit('chat.message', {
userid: myId,
lobby,
username: username,
message
})
this.setState({message: ''});
}
}
handleInputChange = event => this.setState({message: event.target.value});
handleTesteChange = event => this.setState({message: event.target.value});
handleTesteSubmit = event => {
event.preventDefault()
if (message.trim()) {
socket.emit('chat.message', {
userid: myId,
message
})
this.setState({message: ''});
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…