我正在使用NExtjS和react-redux为管理面板创建一个登录页面和 Jmeter 板。下面是我尝试过的代码。如果我使用ID和密码登录,我可以登录并从状态中获取所有值,一切都正常。问题是如果我尝试直接访问 Jmeter 板URL,它会显示Cannot read properties of null (reading 'name')
我如何将用户重定向到登录页面,而不是返回语句???
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';
const Dashboard = () => {
const { auth } = useSelector((state) => state);
const router = useRouter();
console.log(auth)
// I can get all the objects from state and cookies are set as state for browser reload so everything is fine here.
useEffect(() => {
if (!auth.userInfo && auth.userInfo.role == 'user') {
router.push('/admin');
console.log('I am here');
}
}, []);
return <h1>{auth.userInfo.name}</h1>;
};
export default dynamic(() => Promise.resolve(Dashboard), { ssr: false });
1条答案
按热度按时间rqenqsqc1#
最后我找到了解决这个问题的正确方法。正确的方法是: