【发布时间】:2021-11-27 14:56:50
【问题描述】:
所以我需要阻止用户在选择了个人资料后返回个人资料页面 (/profile)。 我将选择的配置文件存储在应用程序状态中。
想要的场景:用户转到 /profile,选择一个配置文件,然后转到“/”(这是我的家),如果他愿意,可以导航到 /exams。 但是,他不能回到 /profile,因为他已经在应用程序内部,并且在状态中存储了一个配置文件。如果他尝试通过浏览器后退箭头或什至在 url 中输入 /profile 转到 /profile,则当前页面只会重新加载。
实现这一目标的最佳方法是什么?
OBS:这个 const { id } = useSelector... 是从状态中检索配置文件的 const,所以我必须使用它作为条件,但我不知道如何。
因此,如果用户的 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;
【问题讨论】:
-
这能回答你的问题吗? Simple Conditional Routing in Reactjs
标签: javascript reactjs react-redux react-router react-router-dom