无法获取组件外部的redux状态



我的身份验证用户的redux状态看起来像:

auth:{
user: {
created_at: "2021-05-12T06:08:57.000000Z"
email: "johndoe@gmail.com"
id: 1
name: "John Doe"
permissions: ["product-view", "product-create", "product-update", "product-destroy", "category-view",…]
role: "superAdmin"
role_id: 1
updated_at: "2021-05-12T06:08:57.000000Z"
}
}

我正在尝试检查用户是否有权限或没有使用此权限数组。为此,我创建了一个实用程序文件authUser.js,看起来像:

import _ from "lodash";
import { store } from "../store";
let adminRole = ["superAdmin", "admin"];
const state = store.getState();
const currentUser = state.auth.user;
export async function havePermission(permission) {
console.log("currentUser >>", currentUser);
console.log("permission >>", permission);
if (isAdmin()) {
return true;
}
if (_.includes(currentUser.permissions, permission)) {
return true;
}
}
export async function isAdmin() {
if (adminRole.includes(currentUser.role)) {
return true;
}
}
export default {
isAdmin,
havePermission,
};

我从
侧边栏.jsx调用此函数

import authUser from "../../../utils/authUser";
const Sidebar = () => {
return(
<div>
{console.log(` have permission called >>
${authUser.havePermission("product-view")}
`)}
{authUser.havePermission("view-name") &&
"Dummy Name"}
</div>
)
}

我正在将商店导出为export { persistor, store };

目前这些数据显示在console.log 上

currentUser >> {}
permission >> product-view
have permission called >> [object Promise]                      
currentUser >> {}
permission >> view-name

找不到currentUser为空对象的原因。我该如何解决这个权限检查,因为它目前返回的是空对象,尽管我可以在redux选项卡上清楚地看到这个用户对象的值。

在实用程序文件中,对getState()的调用最初只会被调用,因此无论何时尝试访问currentUser,都将处于默认状态,此后没有应用任何更新。

const state = store.getState();
const currentUser = state.auth.user;

您需要将上述调用移动到一个选择器中,该选择器将被赋予当前状态,并计算出当前用户是否具有权限,即

export async function havePermission(state, permission) {
console.log("currentUser >>", state.auth.user);
console.log("permission >>", state.auth.user.permissions);
if (isAdmin(state.auth.user)) {
return true;
}
if (_.includes(state.auth.user.permissions, permission)) {
return true;
}
return false;
}

您可以使用react-redux中的useSelector挂钩,它将通过当前的redux状态,然后您可以将其传递给havePermission,以确定用户是否具有特定的权限。

import { useSelector } from "react-redux";
import {havePermission} from "../../../utils/authUser";
const Sidebar = () => {
const hasProductPermission = useSelector((state) => havePermission(state, "product-view"));
const hasViewNamePermission = useSelector((state) => havePermission(state, "view-name"));
return(
<div>
{console.log(` have permission called >>
${hasProductPermission}
`)}
{hasViewNamePermission &&
"Dummy Name"}
</div>
)
}

此外,您可以将useSelector调用移动到自定义权限挂钩中:

import { useSelector } from "react-redux";
import { havePermission } from "../../../utils/authUser";
const usePermission = (permission) => {
return useSelector((state) => havePermission(state, permission);
}
const Sidebar = () => {
const hasProductPermission = usePermission("product-view");
}

相关内容

  • 没有找到相关文章

最新更新