我正在开发一个基于 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() 依赖列表。
答案 0 :(得分:0)
仔细研究一下,您似乎无法在 removeItem = (itemToremove) => {
this.props.removeFromFoodList(itemToremove)
}
render() {
return (
<FlatList
data={this.props.foodList}
renderItem={({ item }) => (
<View>
<TouchableOpacity
onLongPress={this.removeItem(item)}
>
<Text>{item.foodName}</Text>
<Text>
{item.calories}
</Text>
<MaterialIcons name="arrow-forward-ios" />
</TouchableOpacity>
</View>
)}
keyExtractor={item => item.id}
/>
)
}
中正确使用 React 控制的引用。 here 中描述的解决方案和 this question 上的几个答案可能会进一步帮助您。
简而言之,您的 useEffect
在引用设置之前被调用。相反,使用回调作为参考:
useEffect