【问题标题】:Getting TypeError in react useRef() hook在 react useRef() 钩子中获取 TypeError
【发布时间】:2021-07-20 17:05:08
【问题描述】:

我正在开发一个基于 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() 依赖列表。

【问题讨论】:

  • myVideo 实际在哪里使用,除了你读的时候? myVideo.current 将永远是 undefined 除非你手动设置它(对于可变的 refs)或者如果它被传递给一个 DOM 元素而不是由 React 设置。
  • myVideo 在组件中用作视频属性的来源
  • 作为来源,如src?我可以看到您正在尝试使用它来设置视频的srcObject,因此我假设您应该使用 ref 作为&lt;video ref={myVideo} .../&gt;。如果您没有那样使用它,或者没有以正确的方式使用它,那就是错误所在。
  • 我按照你说的方式使用它

标签: javascript reactjs react-redux react-hooks


【解决方案1】:

仔细研究一下,您似乎无法在 useEffect 中正确使用 React 控制的引用。 here 描述的解决方案和 this question 上的几个答案可能会进一步帮助您。

简而言之,您的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} ... />;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2020-03-07
    • 2022-10-12
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    相关资源
    最近更新 更多