React受保护路由不适用于后端/Redux

nhhxz33t  于 2023-03-02  发布在  React
关注(0)|答案(1)|浏览(197)

嘿,所以我的新的用户试图查看他们的业务的某些细节的保护路线是行不通的。后端验证如果用户是一个“成员”,如果真的会让他们继续。后端发送正确的有效负载,我可以看到,在redux开发人员工具,但控制台日志最初是未定义的。它'直到用户被重定向回来并第二次单击链接后,控制台日志才会等于true。我知道这是一个异步问题,但我无法解决它。我我也试过使用setTimeout(),但也不起作用。
受保护路由组件:

import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { businessDetail } from "../../redux/actions/business";
import { Outlet, Navigate, useParams } from "react-router-dom";

function BusinessRoute (props) {
  const { businessSlug } = useParams();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(businessDetail(businessSlug))

    console.log(business.member)
  }, [])

  const business = useSelector(state => state.business.business_page,)

  return (
    business?.member ? <Outlet /> : <Navigate to="/your-businesses" />
  )
}

export default (BusinessRoute);

还原状态:

谢谢

vatpfxk5

vatpfxk51#

在确定是通过Outlet组件呈现受保护内容还是通过Navigate组件重定向之前,请等待business.member值定义完毕。

function BusinessRoute () {
  const dispatch = useDispatch();

  const { businessSlug } = useParams();  

  useEffect(() => {
    dispatch(businessDetail(businessSlug));
  }, [dispatch, businessSlug]);

  const business = useSelector(state => state.business.business_page);

  if (business.member === undefined) {
    return null; // or loading indicator/spinner/etc
  }

  return business.member
    ? <Outlet />
    : <Navigate to="/your-businesses" replace />;
}

相关问题