[英]Next.js router.push() redirects but doesn't render page
我正在 localhost:3000 中运行 Next.js 应用程序,如果没有用户数据,它最初会重定向到登录页面。 最初它重定向到登录页面,但它没有呈现,我得到了这个错误:
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
in Index (at _app.js:7)
in ApolloProvider (at _app.js:6)
in MyApp
in ErrorBoundary (created by ReactDevOverlay)
in ReactDevOverlay (created by Container)
in Container (created by AppContainer)
in AppContainer
in Root
我不确定我做错了什么。 我是 Next.js 的新手,不知道如何处理这个问题。
任何帮助将不胜感激。
这是我的代码:
import Layout from '../components/Layout';
import Client from '../components/Client';
import { useRouter } from 'next/router';
import { useQuery } from '@apollo/client';
import { queryGetClientsVendor } from '../graphql/queries';
import Link from 'next/link';
const Index = () => {
const router = useRouter();
const { data, loading, error } = useQuery(queryGetClientsVendor);
console.log(data, loading, error);
if (loading) return 'Loading...';
if (!data.getClientsVendor) {
return router.push('/login');
}
return (
<div>
<Layout>
<h1 className='text-2xl text-gray-800 font-normal'>Index</h1>
<Link href='/newclient'>
<a className='bg-blue-800 py-2 px-5 mt-5 inline-block text-white rounded text-sm hover:bg-gray-800 mb-3 uppercase font-bold'>
New Client
</a>
</Link>
<table className='table-auto shadow-md mt-10 w-full w-lg'>
<thead className='bg-gray-800'>
<tr className='text-white'>
<th className='w-1/5 py-2'>Name</th>
<th className='w-1/5 py-2'>Company</th>
<th className='w-1/5 py-2'>Email</th>
<th className='w-1/5 py-2'>Delete</th>
<th className='w-1/5 py-2'>Edit</th>
</tr>
</thead>
<tbody className='bg-white'>
{data.getClientsVendor.map((client) => (
<Client key={client.id} client={client} />
))}
</tbody>
</table>
</Layout>
</div>
);
};
export default Index;
您还可以在 github 上查看整个代码项目 => https://github.com/francislagares/crm-react
提前致谢。
你不返回router.push
- 它不是React child
。
我建议你尝试:
if (!data.getClientsVendor) {
router.push('/login');
return <p>Redirecting...</p>;
}
谢谢。
好吧,在深入研究 Next 文档之后,我终于可以让它与 getInititalProps 一起工作:
Index.getInitialProps = async (ctx) => {
if (ctx && ctx.req) {
ctx.res.writeHead(302, { Location: '/login' });
ctx.res.end();
} else {
return {};
}
};
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.