React Hook setstate运行两次

时间:2020-08-14 02:33:41

标签: reactjs react-hooks

我有一个由socket.io的事件调用的函数:

const [room, setRoom] = useState({})
const [messages, setMessages] = useState([])

function reciveMessage(message) {
 if (room.id == message.roomid) {
  setMessages(messages => [...messages, message])
 }
}

房间状态值过时

如果我尝试解决该问题,

setRoom(room => {
 if (room.id == event.data.source.conId) {
  setMessages(messages => [...messages, message])
 }
 return room
})

房间值是最新的,但是setMessage运行两次,有没有更好的方法?

1 个答案:

答案 0 :(得分:1)

套接字消息是一种副作用,因此请在useEFfect中处理它。

useEffect(() => {
    // do whatever it is to set up the message subscription/connection
    // and call `setMessages([...messages, message])` when
    // one is received in the handler/callback
    return () => {
        // clean-up, e.g., closing connection, etc. 
    }

}, 
// will only re-run the effect if the id changes
[room.id])

setMessages仅在收到消息时被调用。如果room.id发生更改,则useEffect代码将再次运行,潜入新房间。