gpt4 book ai didi

reactjs - 在 Next.js SSR 中检测设备的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-04 17:27:59 41 4
gpt4 key购买 nike

我有 <MobileLayout /> , <DesktopLayout /> .我正在使用 Next.js用于服务器端渲染。
我注意到有很多著名的 ui 库都有移动检测组件,比如 <Respnosive /> Semantic-UI-React 中的组件。但所有这些都是客户端方法,在 SSR 上无法正常工作

我阅读了一些文件,结论是我应该检查 user-agent服务器端req.headers .在 Next.js 中,检测设备并有条件地呈现 MobileLayout 之一的正确方法是什么?/DesktopLayout ?

我试过的

_app.js

import isMobile from 'ismobilejs'

...

function Homepage({ Component, pageProps, mobile }){
return (
mobile ?
<MobileLayout><Component {...pageProps} /></MobileLayout> :
<DesktopLayout><Component {...pageProps} /></DesktopLayout>
)
}

HomePage.getInitialProps = async (appContext) => {
const userAgent = appContext.ctx.req.headers['user-agent']
const mobile = isMobile(userAgent).any
const appProps = await App.getInitialProps(appContext)
return { ...appProps, mobile }
}

但问题是 _app.js 上的 getIntialProps执行每个页面加载。与客户端一起移动页面, appContext.ctxundefined所以它会省略错误。我认为这种方法可能会阻止一些 nextjs 内置优化。

Error in error page getInitialProps: TypeError: Cannot read property 'headers' of undefined



那么在 Next.js 中检查设备的正确方法是什么?

最佳答案

如果您想使用 userAgent 检测用户的设备,您最好的选择是 this answer :

IndexPage.getInitialProps = ({ req }) => {
let userAgent;
if (req) { // if you are on the server and you get a 'req' property from your context
userAgent = req.headers['user-agent'] // get the user-agent from the headers
} else {
userAgent = navigator.userAgent // if you are on the client you can access the navigator from the window object
}
}

(请注意,如果您有 Next 9.3 或更新版本,您应该在可能的情况下 actually be using getServerSidePropsgetStaticProps,但有时无法替代 getInitialProps 功能。)

然而,Mozilla 的人们 advise :

It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!



isMobile package的制造商你甚至在导入警告:

You might not need this library. In most cases, responsive design solves the problem of controlling how to render things across different screen sizes.



所以,看看你是否可以使用 CSS3 media queries有条件地渲染某些元素或改变它们的大小等,而不是完全独立的移动和桌面布局组件。但是,您可能会遇到无法使任何替代选项起作用的边缘情况。

如果您打算保留当前设置并在其他页面上使用您的两个布局,您可以考虑将它们组合成一个父级 <Layout>有条件地呈现一个或另一个的组件,因此您不必将该逻辑复制到每个页面中:
export const Layout = (props) => {
return (
props.mobile ?
<MobileLayout>{props.children}</MobileLayout> :
<DesktopLayout>{props.children}</DesktopLayout>
)
}

关于reactjs - 在 Next.js SSR 中检测设备的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62143394/

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