繁体   English   中英

在反应 useRef() 钩子中获取 TypeError

[英]Getting TypeError in react useRef() hook

我正在开发一个基于 webRTC API 的应用程序,并在 React 中使用 useRef() 钩子,但出现错误

Error:  TypeError: myVideo.current is undefined
    ContextProvider SocketContext.js:27
    promise callback*ContextProvider/< SocketContext.js:23
    React 5
    unstable_runWithPriority scheduler.development.js:468
    React 3
    workLoop scheduler.development.js:417
    flushWork scheduler.development.js:390
    performWorkUntilDeadline scheduler.development.js:157
    js scheduler.development.js:180
    js scheduler.development.js:645
    Webpack 21

和上下文的代码是

const myVideo = useRef();
//const myVideo = useRef(null);  tried this also but not solved 
  const userVideo = useRef();
  const connectionRef = useRef();

  useEffect(() => {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
      .then((currentStream) => {
        setStream(currentStream);

        myVideo.current.srcObject = currentStream;
      })
      .catch((err) => {
        console.log("Error ", err);
      })

    socket.on('me', (id) => setMe(id));

    socket.on('callUser', ({ from, name: callerName, signal }) => {
      setCall({ isReceivingCall: true, from, name: callerName, signal });
    });
  }, []);

我试过添加 myVideo || myVideo.current 是 useRef() 依赖列表。

深入研究一下,似乎您无法在useEffect正确使用 React 控制的useEffect 此处描述的解决方案和有关此问题的几个答案可能会进一步帮助您。

简而言之,您的useEffect在引用设置之前被调用。 相反,使用回调作为参考:

const myVideo = useCallback(video => {
    if (!video) return; // video object no longer available
    // You now have the video object
    // either set the `srcObject` here, or store `video` to set it later
}, []);

// somewhere else
return <video ref={myVideo} ... />;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM