//SocketProvider.tsx
import React, { useContext, useEffect, useState } from 'react';
import { io } from 'socket.io-client';
/**
* 创建 context
*/
const SocketContext = React.createContext(null)
/**
* 调用 socket
*/
export function useSocket() {
return useContext(SocketContext)
}
/**
* 提供 socket
* @param children 子组件
*/
export function SocketProvider({ children }) {
const [socket, setSocket] = useState()
useEffect(()=>{
const newSocket = io('ws://localhost:7001')
setSocket(newSocket)
return () => newSocket.close()
}, [])
return (
<SocketContext.Provider value={socket}>
{children}
</SocketContext.Provider>
)
}
//app.tsx 中使用 SocketProvider
<SocketProvider>
{children}
</SocketProvider>
//子组件中调用 socket
const socket= useSocket()
console.log(socket)
//控制台 socket 对象
acks: proto: Object connected: false disconnected: true
1
joesonw 2020-12-08 14:13:38 +08:00
socket.on('connect')之后才算连上吧
用 https://github.com/streamich/react-use/blob/master/docs/useAsyncFn.md 这个包一下 |
2
zhongrs232 2020-12-08 18:45:07 +08:00
巧了这头像
|