服务器端的条件渲染 [英] Conditional Rendering on Server Side

查看:76
本文介绍了服务器端的条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景
我正在使用next.js进行服务器端渲染,并使用react.js进行客户端.

Background
I am using next.js for server side rendering and react.js for client side.

目标
希望基于服务器端的窗口大小进行条件渲染.就像200px宽的渲染A组件和400px宽的渲染B组件一样.

Goal
Want to do conditional rendering on the basis of window size in server side. Like for 200px width render A component and for 400px width render B component.

问题
在服务器端,我们无法访问window对象,也无法了解客户端使用的设备.因此AFAIK我们无法在服务器端进行条件渲染.

Problem
In server side, we have no access to the window object and we have no idea about the device our client is using. So AFAIK we cant do conditional rendering on server side.

想法
我已经想到了一些解决方案,但不知道是否可能-
1.通过http请求将设备信息或窗口对象作为json发送.
2.不要在服务器端渲染条件组件,而在客户端重新渲染(水合)它们.

Thoughts
I have thought of some solutions, but don't know is it possible or not -
1. Send the device info or window object as json with the http request.
2. Don't render the conditional components in server side and re-render (hydrate) them on client side.

但是我不知道什么是最佳实践,什么比其他方法更有效.也欢迎提出新建议.

But I don't know what is the best practice and what is more efficient than other. New suggestions are also welcome.

推荐答案

考虑使用下一种方法:

  1. 在服务器端,您可以通过分析用户代理来预测设备类型 借助 mobile-detect 包并将期望值传递给 在反应尺寸顶部创建的同构HOC 设置预测的"屏幕尺寸以在服务器端工作.
  2. 根据您的业务逻辑包装条件逻辑 您创建的具有自适应HOC的结构
  3. ...
  4. 利润
  1. On server side you can predict device type by parsing user-agent with help of mobile-detect package and pass expected values to an isomorphic HOC created on top of react-sizes which allows to setup "predicted" screen sizes to work on server side.
  2. Wrap your conditional logic with appropriate to your business logic structures with adaptive HOC you've created
  3. ...
  4. Profit

至少要注意接下来的情况:

Be aware of at least next cases you should take care of:

  1. 桌面用户代理的窄屏将按原样呈现 桌面,但可能会像MatchMedia一样开始在客户端重新渲染 会为客户做事
  2. 任何缓存层都应将已解析的设备类型包括在缓存键中 因此您将不会缓存可能损坏的布局.
  1. Narrow screens of desktop user-agents will be rendered as for desktop, but might start re-rendering on client side, as MatchMedia gonna do its work on client
  2. Any caching layer should include parsed device type into cache key so you will not cache potentially broken layout.

这篇关于服务器端的条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆