【问题标题】:how to Redirect to another page in next.js based on css media query?如何根据 css 媒体查询重定向到 next.js 中的另一个页面?
【发布时间】:2020-04-24 14:57:09
【问题描述】:

我是 Next.js 的新手,我有以下情况。我想将用户重定向到路由/messages,如果他基于css媒体查询键入路由/messages/123,因此如果他是移动的,我们将不会重定向,如果他在浏览器中,则 redirect 。 我试过下面的代码

import React, { useLayoutEffect } from 'react';
import { useRouter, push } from 'next/router';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import Layout from '../components/Customer/Layout/Layout';
import Chat from '../components/Customer/Chat/Chat';

const Messages = () => {
 const { pathname, push } = useRouter();
 const matches = useMediaQuery('(min-width:1024px)');

 useLayoutEffect(() => {
   console.log('I am about to render!');
   if (matches && pathname === '/messages') {
     console.log('match!');
     push('/');
   }
 }, [matches, pathname, push]);

 return (
   <Layout currentURL={pathname}>
     <Chat />
   </Layout>
 );
};

export default Messages;

问题是组件在重定向之前渲染了两次

【问题讨论】:

    标签: reactjs material-ui react-hooks next.js server-side-rendering


    【解决方案1】:

    但您可能应该使用useEffect,因为您没有尝试进行任何 DOM 操作或计算。

    useLayoutEffect:如果您需要改变 DOM 和/或需要执行测量

    useEffect:如果您根本不需要与 DOM 交互,或者您的 DOM 更改是不可观察的(说真的,大多数时候您应该使用它)。

    您应该会立即采取行动。

    编辑:

    您可以使用 Next JS getInitialProps 检查请求标头并确定请求是来自移动设备还是桌面设备,然后从那里重定向。

    getInitialProps({ res, req }) {
        if (res) {
          // Test req.headers['user-agent'] to see if its mobile or not then redirect accordingly
          res.writeHead(302, {
            Location: '/message'
          })
          res.end()
        }
        return {}
      }
    

    【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多