【发布时间】:2019-07-26 18:53:18
【问题描述】:
我正在使用 react-static 来生成静态网站。使用来自the new hook API 的useLayoutEffect,我在静态渲染阶段收到此警告(与服务器端渲染相同的API):
Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format.
This will lead to a mismatch between the initial, non-hydrated UI and th e intended UI.
To avoid this, useLayoutEffect should only be used in components that render exclusively on the client.
这当然是有道理的。 但是,当确定不会出现任何不匹配时,消除此警告的好选择是什么?
在我的布局效果中,我只是在 body 标签中添加了一点 CSS,因此在客户端的水合阶段不会出现任何不匹配(因为 body 不是 React 的业务)。
React 强烈禁止使用条件挂钩,但在那种 非常 特定的情况下,做类似这样的事情是否有意义:
if(typeof window !== 'undefined')
useLayoutEffect(() => {
document.body.style.overflowY = loading ? 'hidden' : 'visible'
},
[loading]
)
正确的方法是什么?
【问题讨论】:
标签: reactjs server-rendering react-static