【发布时间】: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