请参阅下面的代码,我在项目中使用 SSR ,但有些组件可以在浏览器端呈现,因为它使用window
或document
对象。所以我做一个交换机,在服务器端:返回null,并在浏览器端返回真实组件。但我得到了校验和错误。我该怎么办?
render() {
if (!process.env.BROWSER) {
return null;
}
else {
const OwlCarousel = require('react-owl-carousel').default;
return <OwlCarousel
className="owl-theme"
loop margin={10} nav
>
<div className="item" style={{backgroundColor:'#3EA5E9'}}><h4>1</h4></div>
<div className="item"><h4>2</h4></div>
<div className="item"><h4>3</h4></div>
<div className="item"><h4>4</h4></div>
<div className="item"><h4>5</h4></div>
<div className="item"><h4>6</h4></div>
<div className="item"><h4>7</h4></div>
<div className="item"><h4>8</h4></div>
<div className="item"><h4>9</h4></div>
<div className="item"><h4>10</h4></div>
<div className="item"><h4>11</h4></div>
<div className="item"><h4>12</h4></div>
</OwlCarousel>;
}
}
答案 0 :(得分:2)
示例组件
import { Component } from 'react'
export default class MyComponent extends Component {
state = { render: false }
componentDidMount() {
if (process.env.BROWSER) this.setState({ render: true })
}
render() {
return this.state.render && <ComponentToRender />
}
}