javascript - 当代码需要设备宽度时,ReactDOMServer 如何表现?

标签 javascript reactjs server-side-rendering react-dom react-dom-server

我有以下钩子(Hook),用于在整个应用程序中构建响应式组件。

我正在考虑实现服务器端渲染。

useWindowWidth.js

import {useEffect, useRef, useState} from 'react';

function useWindowWidth() {
  const hasResized = useRef(false);
  const [windowSize,setWindowSize] = useState(window.innerWidth);

  useEffect(() => {

    function handleResize() {
      if (hasResized.current === true) {
        return;
      }
      hasResized.current = true;
      throtled_forceUpdate();
    }

    function throtled_forceUpdate() {
      setTimeout(()=>{
        // console.log('I will be updated!');
        // console.log(window.innerWidth);
        setWindowSize(window.innerWidth);
        hasResized.current = false;
      },250);
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowSize;

}

export default useWindowWidth;

App.js

import React from 'react';
import useWindowWidth from './hooks/useWindowWidth';

function App(props) {

  const windowWidth = useWindowWidth();

  return(
    windowWidth > 1200 ?
      <DesktopLayout/>
    : <MobileLayout/>
  );
}

ReactDOMServer

ReactDOMServer.renderToString(App);

当 ReactDOMServer 遇到这样的事情时,它会采取什么行为?这种情况的解决方法是什么?

最佳答案

服务器端无法获取窗口宽度。解决方法是使用传入请求中的用户代理来确定应在服务器上呈现哪个组件。

const deviceType = useDeviceType();
return deviceType === 'mobile' ? <MobileLayout /> : <DesktopLayout />;

或者作为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.

关于javascript - 当代码需要设备宽度时,ReactDOMServer 如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923148/

相关文章:

javascript - Html Php Ajax 图片上传

javascript - 使用工厂和 Controller 返回数据

reactjs - 创建文本输入 Redux 的最佳方式是什么

Angular 通用 : How to create an app shell and only pre-render the shell?

reactjs - 服务器端渲染通过 Ajax 加载状态的 React 组件

javascript - 奇怪的匿名javascript函数调用

javascript - 使用 highcharts api 和 mysql 显示饼图

intellij-idea - 如何在同一个编辑器中使用 PyCharm 和 WebStorm

javascript - 我需要在 Redux 应用程序的代码中的这些地方写什么(重新制作纯粹的 redux react )?

javascript - 如何在 vue/nuxt 中结合 ssr 根据屏幕尺寸有条件地正确渲染 html