reactjs TypeError:无法读取React中undefined的属性(阅读'on')

nle07wnf  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(161)

我得到这个错误“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时,我正在尝试分配房间。

dbf7pr2w

dbf7pr2w1#

基于这个socket docs,这是一个第三方库,你不必在你的socket.jsx中使用SocketProvideruseMemo。并且在创建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:对于输入错误中不受控制的更改,您不应该将useState设置为null and undefined。它应该始终是空字符串""
我希望这对你有帮助。

相关问题