加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

meteor – React SSR – 处理window.height / width

发布时间:2020-12-15 20:31:19 所属栏目:百科 来源:网络整理
导读:我正在使用React和SSR FlowRouter. 由于这条线: var height = (Meteor.isClient ? window.innerHeight : 0);div style={{top: height+'px' }} 我收到这样的警告: 警告:React尝试在容器中重用标记,但校验和无效.这通常意味着您正在使用服务器呈现,并且在服
我正在使用React和SSR FlowRouter.

由于这条线:

var height = (Meteor.isClient ? window.innerHeight : 0);
<div style={{top: height+'px' }}>

我收到这样的警告:

警告:React尝试在容器中重用标记,但校验和无效.这通常意味着您正在使用服务器呈现,并且在服务器上生成的标记不是客户端所期望的. React注入了新的标记来补偿哪些有效,但是你已经失去了服务器渲染的许多好处.相反,弄清楚为什么生成的标记在客户端或服务器上是不同的.

我知道这是因为客户端和服务器代码之间的差异(我无法访问我的服务器上的窗口).

有没有办法避免这种警告?

解决方法

您面临的警告是由于服务器上最初呈现的html与客户端之间的校验和错误.正如您正确指出的那样,这是因为您在服务器上没有窗口对象,因此无法计算window.innerHeight.这导致渲染的html在div的style属性中不同并导致警告.

一种可能的解决方法是将height变量移动到组件的状态并将其设置为初始状态0.然后执行检查

this.setState({height: (Meteor.isClient ? window.innerHeight : 0)});

在componentWillMount中并在此处设置正确的高度.这样,客户端和服务器的初始渲染将是相同的.但是,由于componentDidMount仅在客户端上调用,因此当状态更改时,它将从窗口重新呈现具有正确高度的组件.

从docs

If you intentionally need to render something different on the server and the client,you can do a two-pass rendering. Components that render something different on the client can read a state variable like this.state.isClient,which you can set to true in componentDidMount(). This way the initial render pass will render the same content as the server,avoiding mismatches,but an additional pass will happen synchronously right after hydration. Note that this approach will make your components slower because they have to render twice,so use it with caution.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读