TypeError:无法在 React 中读取未定义的属性(读取“on”)

问题描述 投票:0回答:1

我收到这个错误“无法读取未定义的属性(读取‘on’) 在 Home.jsx:17:1" 这是主页(在客户端)代码:

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 时,我正在尝试分配房间。

reactjs socket.io webrtc typeerror
1个回答
0
投票
基于这个

socket docs,这是一个第三方库,你不必在你的 socket.jsx 中使用 SocketProvider

useMemo
。在创建 Hooks 时,无需为使用第三方库创建任何上下文。

你可以在

socket.jsx

中做这些:

import { io } from "socket.io-client"; export const useSocket = () => { const socket = io("http://localhost:8001"); return socket; };
并在

HomePage.jsx

中做一些改变:

const socket = useSocket(); // remove curly braces from the socket //... const [email, setEmail] = useState(""); //set it as empty string not `null or undefined` it gives uncontrolled change input error const [roomId, setRoomId] = useState(""); //...
PS:对于 

uncontrolled changing in an input error 你不应该将 useState

 设置为 
null and undefined
。它应该总是一个空字符串
""
.

我希望这对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.