从状态提取数据时无法读取 null 的属性
我试图在标志为 true 时显示导航项,但问题是,当我尝试从中获取以下数据时,它返回给我未定义,我为此创建了以下内容:
let navigate = useNavigate();
const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
const { userInfo } = userSignin;
const checkAdmin = useCallback(() => {
if (userInfo) {
if (typeof userInfo.user === "undefined") {
return null;
} else {
return userInfo.user.isAdmin;
}
} else {
return null;
}
}, []);
useEffect(() => {
checkAdmin();
if (!userInfo.user.isAdmin) {
navigate("/");
}
}, [checkAdmin]);
我执行了 checkAdmin 函数,因为在此之前,我有 userInfo.user.isAdmin ,它返回给我未定义。
{checkAdmin() && (
<NavbarItem
component='li'
onMouseEnter={() => setTopMenuIndex(4)}
onMouseLeave={() => setTopMenuIndex(-1)}
>
<Box
style={{ whiteSpace: "nowrap" }}
component='a'
{...{ href: "/createItem" }}
>
{topMenuIndex === 4 && <Tippy topMenuIndex={topMenuIndex} />}
Admin Dashboard
</Box>
</NavbarItem>
)}
现在我想确保,如果您没有该标志,您将被重定向到主页,但使用 userInfo.user.isAdmin 现在返回 null。我怎样才能更好地重新编码这个逻辑,或者我怎样才能至少使这个 useEffect 正确工作。
I'm trying to display a navigation item when a flag is true, but the problem is, when I try to get the following data from it, it returned me undefined, I created the following for that:
let navigate = useNavigate();
const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
const { userInfo } = userSignin;
const checkAdmin = useCallback(() => {
if (userInfo) {
if (typeof userInfo.user === "undefined") {
return null;
} else {
return userInfo.user.isAdmin;
}
} else {
return null;
}
}, []);
useEffect(() => {
checkAdmin();
if (!userInfo.user.isAdmin) {
navigate("/");
}
}, [checkAdmin]);
I did the checkAdmin function, because before that I had userInfo.user.isAdmin and it returned me undefined.
{checkAdmin() && (
<NavbarItem
component='li'
onMouseEnter={() => setTopMenuIndex(4)}
onMouseLeave={() => setTopMenuIndex(-1)}
>
<Box
style={{ whiteSpace: "nowrap" }}
component='a'
{...{ href: "/createItem" }}
>
{topMenuIndex === 4 && <Tippy topMenuIndex={topMenuIndex} />}
Admin Dashboard
</Box>
</NavbarItem>
)}
Now I want to make sure that if you don't have that flag, you will get redirected to the homepage, but using the userInfo.user.isAdmin is returning null now. How can I recode this logic to be better or how can I make at least this useEffect work correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您在数组内的 useEffect 中传递 checkAdmin,但它是一个函数。据我所知,您只能传递状态或道具来刷新组件或重新渲染。
我不确定到底要问什么,但据我说。
Firstly you are passing checkAdmin in useEffect inside an array, but it is a function. According to my knowledge you can only pass state or props to refresh the component or re-render.
I am not sure what exactly the ask was but, according to me.