gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:57:32 24 4
gpt4 key购买 nike

我有以下钩子(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com