首页 > 解决方案 > 阻止用户进入个人资料页面

问题描述

因此,我需要防止用户在选择了个人资料后返回个人资料页面(/profile)。我将选择的配置文件存储在应用程序状态中。

想要的场景:用户转到 /profile,选择一个配置文件,然后转到“/”(这是我的家),如果他愿意,可以导航到 /exams。但是,他不能回到 /profile,因为他已经在应用程序内部,并且在状态中存储了一个配置文件。如果他尝试通过浏览器后退箭头或什至在 url 中键入 /profile 转到 /profile,则当前页面只会重新加载。

实现这一目标的最佳方法是什么?

OBS: this const { id } = useSelector...是从状态中检索配置文件的常量,所以我必须使用它作为条件,但我不知道如何。

因此,如果用户的 id 不为空(这意味着他已经选择了个人资料),他就无法返回个人资料。除此之外,他可以访问/profile。

下面是我的 route.tsx :

const Exams = lazy(() => import('../pages/private/Exams'));
const Home = lazy(() => import('../pages/private/Home'));
const ProfileSelector = lazy(() => import('../pages/private/ProfileSelector'));
const { id } = useSelector((state: RootState) => state.profile);

const AppRoutes = () => {
    return (
        <Router history={history}>
            <Suspense fallback={<LoadingPage />}>
                <Switch>
                    <Route exact path={'/'} component={Home} />
                    <Route exact path={'/exams'} component={Exams} />
                    <Route exact path={'/profile'} component={ProfileSelector} />
                </Switch>
            </Suspense>
        </Router>
    );
};

export default AppRoutes;

我的个人资料商店(如果有任何用处):

    interface UserProfileModel {
    id: string;
    council: string;
    state: string;
    number: string;
    description: string;
}

const initialState: UserProfileModel = {
    id: '',
    council: '',
    state: '',
    number: '',
    description: '',
};

export const userProfileSlice = createSlice({
    name: 'profile',
    initialState,
    reducers: {
        selectProfile: (state, action: PayloadAction<UserProfileModel>) => {
            return {
                ...state,
                ...action.payload,
            };
        },
        clearProfile: () => initialState,
    },
});

export const { selectProfile, clearProfile } = userProfileSlice.actions;

export default userProfileSlice.reducer;

标签: javascriptreactjsreact-reduxreact-routerreact-router-dom

解决方案


当用户选择配置文件时,将状态(例如 profileSelected)设置为 true,然后:

{profileSelected ? null : <Route exact path={'/profile'} component={ProfileSelector} />}

代替

<Route exact path={'/profile'} component={ProfileSelector} />

推荐阅读