我得到这个错误“cannot read properties of undefined(阅读'on')at Home.jsx:17:1”下面是HomePage(在客户端)代码:
import React, { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import {useSocket} from "../providers/socket";
const Homepage = () => {
const { socket } = useSocket();
const navigate = useNavigate();
const [email, setEmail] = useState();
const [roomId, setRoomId] = useState();
const handleRoomJoined = useCallback(({roomId}) => {
navigate(`/room/${roomId}`);
}, [navigate]);
useEffect(() => {
socket.on('joined-room', handleRoomJoined);
return () =>{
socket.off('joined-room', handleRoomJoined);
}
}, [handleRoomJoined, socket])
const handleJoinRoom = () => {
socket.emit("join-room", {emailId: email, roomId});
};
return (
<div className="homepage-containter">
<div className="input-container">
<input value = {email} onChange={e => setEmail(e.target.value)} type="email" placeholder="Enter your email here" />
<input value = {roomId} onChange={e => setRoomId(e.target.value)} type="text" placeholder="Enter your room code" />
<button onClick={handleJoinRoom} type='submit'>Enter Room</button>
</div>
</div>
);
};
export default Homepage
socket.jsx的代码如下:
import React, { useMemo } from "react";
import {io} from 'socket.io-client';
const SocketContext = React.createContext(null);
export const useSocket = () =>{
return React.useContext(SocketContext);
};
export const SocketProvider = (props) => {
const socket = useMemo(() => io("http://localhost:8001"), [])
return (
<SocketContext.Provider value={socket}>
{props.children}
</SocketContext.Provider>
)
};
当用户输入emailId和roomId时,我正在尝试分配房间。
1条答案
按热度按时间dbf7pr2w1#
基于这个socket docs,这是一个第三方库,你不必在你的socket.jsx中使用
SocketProvider
和useMemo
。并且在创建Hooks时不需要创建任何上下文只是为了使用第三方库。你可以在
socket.jsx
中这样做:在
HomePage.jsx
中做一些修改:PS:对于输入错误中不受控制的更改,您不应该将
useState
设置为null and undefined
。它应该始终是空字符串""
。我希望这对你有帮助。