出现这个错误原因是因为在 React 组件中使用,
import AgoraRTC from “agora-rtc-sdk”
import AgoraRTCMedia from “agora-rtc-react”
export default class App extends React.Component {
componentDidMount() {
let client = AgoraRTC.createClient({mode: “live”, codec: “vp8”});
//...
}
//...
}
而 agora-rtc-sdk
插件是依赖浏览器环境中的全局变量 window
的,但在服务端渲染(SSR)的情况下,是没有 window
这个全局变量的。
解决方法是,将代码的执行放入浏览器环境中,即可以在组件内部判断是否是浏览器环境,如果是,再进行渲染。
import React from "react";
export default class AgoraRTCExample extends React.Component {
constructor(props) {
super(props);
this.isClient = typeof window !== "undefined";
this.state = { client: null };
}
componentDidMount() {
if (this.isClient) {
const client = require("agora-rtc-sdk").createClient({ codec: "vp8", mode: "rtc" });
this.setState({ client });
}
}
render() {
if (this.isClient) {
return {this.state.client ? "Client is ready." : "Client is not ready."};
}
return Server side rendering.;
}
}