【发布时间】: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 作为<video ref={myVideo} .../>。如果您没有那样使用它,或者没有以正确的方式使用它,那就是错误所在。 -
我按照你说的方式使用它
-
标签: javascript reactjs react-redux react-hooks