【问题标题】:Not able to access react state from socket event handler function无法从套接字事件处理函数访问反应状态
【发布时间】:2021-01-21 18:17:53
【问题描述】:

我有一个 react 应用程序,我在其中使用 socket.io 进行实时消息传递。我正在尝试在所有反应功能组件中使用通用套接字对象,但在事件处理函数中我无法访问状态对象。

配置:

var socket = io(socketEndPoint)
socket.emit('register', cookies)
export { socket }

聊天组件:

import {socket} from './Config'
export default function ChatComponent(props) {
  const [chats, setChat] = React.useState([{chat_id: 1234}])
  socket.on('message', (data) => {
    console.log(data)
    console.log(chats)
  })
}

console.log(chats) 总是打印一个空数组。

我尝试使用 Context Api 但仍然没有帮助。有什么方法可以访问反应状态。提前致谢。

【问题讨论】:

  • 在此处添加您的代码

标签: reactjs socket.io


【解决方案1】:

这篇文章似乎已经详细说明了答案: https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559

其中还引用了这篇文章:

React useState hook event handler using initial state

更新 2021 反应功能组件

const [chats, setChats] = useState([])

...

socket.on('message', function (messageData) {
    
    setChats((prev) => {
        return [chat, ...prev]
    }
});

【讨论】:

    猜你喜欢
    • 2023-01-04
    • 2016-07-05
    • 2022-07-08
    • 2019-09-21
    • 1970-01-01
    • 2022-08-12
    • 2018-10-22
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多