javascript - 阻止用户进入个人资料页面
问题描述
因此,我需要防止用户在选择了个人资料后返回个人资料页面(/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;
解决方案
当用户选择配置文件时,将状态(例如 profileSelected)设置为 true,然后:
放
{profileSelected ? null : <Route exact path={'/profile'} component={ProfileSelector} />}
代替
<Route exact path={'/profile'} component={ProfileSelector} />
推荐阅读
- svg.js - 在 SVG 中将文本居中
- java - 从 HTML 中解析信息以找出选定的选项
- r - 如何根据其他列的值在 data.table 中创建新列
- amazon-web-services - 如何使用 S3 作为 Maven 存储库?
- docker - phpmyadmin 在 docker 容器中找不到 404
- c# - 在 Xamarin 中导入联系人 - 电子邮件返回 null
- arrays - 在 Angular HTML 模板中渲染嵌套对象数组的最后一个元素
- matlab - 如何解压 12 位“Mono12Packed”号码
- sql-server - 我在 SQL Server 中运行脚本并得到“将数据类型 varchar 转换为数字时出错。”
- sql-server - macOS Catalina 上的 RODBC