Gem*_*mmi 5 server-side meteor reactjs
我正在使用React和SSR FlowRouter.
由于这条线:
var height = (Meteor.isClient ? window.innerHeight : 0);
<div style={{top: height+'px' }}>
Run Code Online (Sandbox Code Playgroud)
我收到这样的警告:
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server.
我知道这是因为客户端和服务器代码之间的差异(我无法访问我的服务器上的窗口).
有没有办法避免这种警告?
您面临的警告是由于服务器和客户端上最初呈现的 html 之间存在校验和错误。window正如您正确指出的那样,这是因为您在服务器上没有该对象,因此无法计算window.innerHeight。这导致渲染的 html 的style属性不同div并导致警告。
一种可能的解决方法是将height变量移至state组件并将其设置为初始状态 0。然后执行检查
this.setState({height: (Meteor.isClient ? window.innerHeight : 0)});
Run Code Online (Sandbox Code Playgroud)
并componentWillMount在此处设置正确的高度。这样客户端和服务器的初始渲染将是相同的。但是,由于仅在客户端上调用,因此它会在更改时以componentDidMount正确的方式重新渲染组件。heightwindowstate
来自文档
如果您有意需要在服务器和客户端上渲染不同的内容,则可以进行两次渲染。在客户端呈现不同内容的组件可以读取状态变量
this.state.isClient,例如 ,您可以将其设置为trueincomponentDidMount()。这样,初始渲染通道将渲染与服务器相同的内容,避免不匹配,但附加通道将在水合后同步发生。请注意,这种方法会使您的组件变慢,因为它们必须渲染两次,因此请谨慎使用。
| 归档时间: |
|
| 查看次数: |
2168 次 |
| 最近记录: |