在 Nextjs 中保护页面免受未登录用户的影响

问题描述 投票:0回答:1

我正在使用 NExtjS 和 react-redux 为管理面板创建登录页面和仪表板。下面是我尝试过的代码。如果我使用 ID 和密码登录,我可以登录并从状态获取所有值,一切正常。 问题是如果我尝试直接访问仪表板 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 });
redux next.js react-redux
1个回答
2
投票

终于找到解决这个问题的正确方法了。正确的做法是:

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

© www.soinside.com 2019 - 2024. All rights reserved.