redux 在Nextjs中保护页面不被未登录用户访问

ckocjqey  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(158)

我正在使用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 });
rqenqsqc

rqenqsqc1#

最后我找到了解决这个问题的正确方法。正确的方法是:

export const getServerSideProps = async (context) => {
  const session = await getSession({ req: context.req });
  if (session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }
  return {
    props: {
      session,
    },
  };
};

相关问题