反应服务器端 return null 并只做浏览器渲染
react server side return null and just do browser rendering
看下面的代码,我在项目中使用了SSR,但是有些组件只能在浏览器端渲染,因为它使用了window
或document
object.So 我做了一个切换,在服务器端:return null,在浏览器端 return 真正的组件。但是我得到了校验和错误。我该怎么办?
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>;
}
}
示例组件
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 />
}
}
看下面的代码,我在项目中使用了SSR,但是有些组件只能在浏览器端渲染,因为它使用了window
或document
object.So 我做了一个切换,在服务器端:return null,在浏览器端 return 真正的组件。但是我得到了校验和错误。我该怎么办?
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>;
}
}
示例组件
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 />
}
}