[英]How does ReactDOMServer behave when code needs the device width?
我具有以下掛鈎,可用於在整個App中構建響應組件。
我正在研究實現服務器端渲染。
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的行為是什么? 這種情況下的解決方法是什么?
無法獲取服務器端的窗口寬度。 一種解決方法是使用傳入請求中的useragent確定應在服務器上呈現哪個組件。
const deviceType = useDeviceType();
return deviceType === 'mobile' ? <MobileLayout /> : <DesktopLayout />;
或如文檔所述 :
如果您有意在服務器和客戶端上渲染其他內容,則可以進行兩遍渲染。 在客戶端呈現不同內容的組件可以讀取狀態變量this.state.isClient,您可以在componentDidMount()中將其設置為true。 這樣,初始渲染過程將渲染與服務器相同的內容,從而避免了不匹配的情況,但是在水化之后,另一個渲染過程將同步進行。 請注意,這種方法會使您的組件變慢,因為它們必須渲染兩次,因此請謹慎使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.