reactjs react状态的值自动设置为其原始值,什么时候发生套接字事件?

3gtaxfhh  于 2023-05-28  发布在  React
关注(0)|答案(1)|浏览(121)

我正在使用WebRTC和Socket.io构建视频通话应用程序。我正在使用Reducer来存储Local Stream的值。但是当事件video:call:accepted发生时,State中的Local Stream的值变为null
代码段

// importing hooks
import React, { useCallback, useEffect, useReducer } from "react";

// importin components
import ReactPlayer from 'react-player'
import Navbar from "../Navigation/Navbar";
import { socket } from "../../socket";
import Peer from "./Peer";

const initialState = {
    stream: null
};

const reducer = (previousState, action) => {
    switch (action?.type) {
        case 'stream':
            return { ...previousState, stream: action?.stream };
    }
};

const WebRTC = () => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const turnOnYourVideo = async () => {
        const constraints = {
            audio: true,
            video: true
        }
        const localStream = await navigator.mediaDevices.getUserMedia(constraints);
        dispatch({ type: 'stream', stream: localStream });
    }

    const handleCallAccepted = useCallback(({ from, ans }) => {
        // Peer.setLocalDescription(ans);
        console.log('from', from);
        console.log('ans', ans);
        console.log('handleCallAccepted', state?.stream);
    }, []);

    useEffect(() => {
        turnOnYourVideo();
    }, []);

    useEffect(() => {
        socket.on('video:call:accepteed', handleCallAccepted);
        return () => {
            socket.off('video:call:accepteed', handleCallAccepted);
        }
    }, []);

    console.log('Local Stream', state?.stream);

    return (
        <React.Fragment>
            <Navbar />
            <ReactPlayer url={state?.stream} width='800px' playing muted />
        </React.Fragment>
    )
};
export default WebRTC;

Console Logs
在挂载阶段,stream的值为null,然后设置为LocalStream,但当事件发生时,它设置为原始值
这里我想获取LocalStream的轨迹

bvjxkvbb

bvjxkvbb1#

在dependencies数组中添加状态?.stream,否则

useEffect(() => {
       turnOnYourVideo().then(()=>{
socket.on('video:call:accepteed', handleCallAccepted);
       return () => {
           socket.off('video:call:accepteed', handleCallAccepted);
socket.disconnect();
       }
});
   }, []);

相关问题