You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
SSR 是在 node 环境下运行 React 代码,而此时 window、document、navigator 等全局属性没有。如果直接使用了这些属性,就会报错 window is not defined, document is not defined, navigator is not defined 等。
⚠️ 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 the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://fb.me/react-uselayouteffect-ssr for common fixes.
服务端渲染(Server-Side Rendering),是指由服务侧完成页面的 HTML 结构拼接的页面处理技术。一般用于解决 SEO 问题和首屏加载速度问题。
由于 SSR 是在非浏览器环境执行 JS 代码,所以会出现很多问题。本文主要介绍 React Hooks 在 SSR 模式下常见问题及解决方案。
问题一:DOM/BOM 缺失
SSR 是在 node 环境下运行 React 代码,而此时 window、document、navigator 等全局属性没有。如果直接使用了这些属性,就会报错
window is not defined, document is not defined, navigator is not defined
等。常见的错误用法是在 Hooks 执行过程中,直接使用了 document 等全局属性。
解决方案
问题二 useLayoutEffect Warning
如果使用了
useLayoutEffect
,在 SSR 模式下,会出现以下警告解决方案
总结:写 Hooks 时需要注意
isBrowser
判断是否在浏览器环境执行useIsomorphicLayoutEffect
来代替useLayoutEffect
参考资料
❤️感谢阅读
关注公众号「前端技术砖家」,拉你进交流群,大家一起共同交流和进步。
The text was updated successfully, but these errors were encountered: