Reactjs 是否可以将MediaStream保存在react挂钩(useState)中?
我在WebRTC上工作。 我声明了一个变量localStream,如Reactjs 是否可以将MediaStream保存在react挂钩(useState)中?,reactjs,webrtc,Reactjs,Webrtc,我在WebRTC上工作。 我声明了一个变量localStream,如 var localStream; 组件外部。localStream最初包含MediaStream,但在调用信令服务器后调用我的回调函数时,变量localStream为空。我想将MediaStream存储在状态中,以便在调用信令服务器后它不会为空 在页面加载->本地流中包含流 从客户端我打电话,它呼叫信令服务器 它从信令服务器回调客户机,这里localStream为空 我尝试了useState(),useState(未定义)它
var localStream;
组件外部。localStream最初包含MediaStream,但在调用信令服务器后调用我的回调函数时,变量localStream为空。我想将MediaStream存储在状态中,以便在调用信令服务器后它不会为空
import ....
const hubUrl = 'https://f1d3e599fe6c.ngrok.io/ConnectionHub';
const conn =
new signalR.HubConnectionBuilder()
.withUrl(hubUrl, signalR.HttpTransportType.WebSockets)
.configureLogging(signalR.LogLevel.Debug)
.withAutomaticReconnect()
.build();
var localStream;
var peerConnectionConfig = { iceServers: [{ url: 'stun:stun.l.google.com:19302' }] };
onst webrtcConstraints = { audio: true, video: true };
const Chat = (props) => {
React.useEffect(() => {
...
}
receivedSdpSignal = (connection, partnerClientId, sdp) => {
console.log('WebRTC: processing sdp signal');
console.log('sdp', sdp);
connection.setRemoteDescription(new RTCSessionDescription(sdp)).then(() => {
console.log('WebRTC: set Remote Description');
if (connection.remoteDescription.type == "offer") {
console.log('WebRTC: remote Description type offer');
console.log('localStream', localStream);
connection.addStream(localStream);
console.log('WebRTC: added stream');
connection.createAnswer().then((desc) => {
console.log('WebRTC: create Answer...');
console.log('WebRTC: Description...');
console.log(desc);
connection.setLocalDescription(desc).then(() => {
console.log('WebRTC: set Local Description...');
console.log(connection.localDescription);
this.sendHubSignal(JSON.stringify({ "sdp": connection.localDescription }), partnerClientId);
}).catch(err => console.log("WebRTC: Error while setting local description", err));
}, err => console.log("WebRTC: Error while creating the answer", err));
} else if (connection.remoteDescription.type == "answer") {
console.log('WebRTC: remote Description type answer');
}
}).catch(err => console.log("WebRTC: Error while setting remote description", err));
}
const initializeUserMedia = () => {
console.log('WebRTC: called initializeUserMedia: ');
mediaDevices.getUserMedia(webrtcConstraints).then((stream) => {
console.log("WebRTC: got media stream");
localStream = stream;
let audioTracks = localStream.getAudioTracks();
if (audioTracks.length > 0) {
console.log(`Using Audio device: ${audioTracks[0].label}`);
}
}).catch(err => console.log("Error getting user media stream.", err));
}
此函数在useffect(){}之外。本地流在此为空。定义“不工作”,并显示您的代码。不工作-为空。很难从提供的代码中分辨问题,您必须添加整个文件,在localStream变量中设置媒体流的位置以及它变为空的位置。我希望您现在有一些想法。我添加了一些代码@阿卜海塞格尔