在我的 Socket 上下文文件中的以下代码中,useState 没有更新套接字值。但是我看到 newSocket 得到了一个非空值。任何人都可以帮忙吗?
import React,{useRef, useEffect, useState} from 'react';
import io from 'socket.io-client';
const SocketContext = React.createContext({
socket:null
});
const SocketContextProvider = (props)=>{
const [socket,setSocket] = useState(null);
let id = props.id;
useEffect(()=>{
let newSocket = io('http://localhost:5000', { query: { id }});
setSocket((p)=>{
return newSocket;
});
console.log('?'+socket);
return (() => {
newSocket.close();
})
}, [props.id]);
return (
<SocketContext.Provider value={{socket:socket}}>
{props.children}
</SocketContext.Provider>
);
};
export default SocketContext;
export {SocketContextProvider};