我尝试创建自定义钩子来调用 DataProvidergetOne()
方法,以根据登录后从 authProvider 获得的用户名获取权限,但是从函数主体调用钩子的持续要求会引发错误,因为我是从方法。
权限从哪里来?'ra-core' 怎么称呼这个getPermissions()
?为什么.then()
getPermissions() 中有一个名为 not a function 的错误?
需要有关于 AuthProvider 这方面的更好的文档来帮助甚至有经验的 react-admin 人员。只是说。
获取权限的钩子:
const useFetchPermissions = ({ emailId }) => {
const dataProvider = useDataProvider();
const [loading, setLoading] = useState(true);
const [error, setError] = useState();
console.log("fetching permissions");
const [permissions, setPermissions] = useState();
useEffect(() => {
dataProvider
.getOne("users/permissions", { id: emailId })
.then(({ data }) => {
setPermissions(data);
setLoading(false);
})
.catch((error) => {
setError(error);
setLoading(false);
});
}, []);
if (loading) return <Loading />;
if (error) return <Error />;
if (!permissions) return null;
return permissions;
};
AuthPRvider 登录方式:
login: () => {
/* ... */
console.log("Logging in..");
//localStorage.setItem("permissions", "CREATE_ITEM");
return tfsAuthProvider.login();
AuthProvider getPermissions 方法:
getPermissions: () => {
const role = localStorage.getItem("permissions");
console.log(role);
//useFetchPermissions(authProvider.getAccount().userName); throw error
return role === null ? Promise.resolve() : role;
},
App.js dataProvider(url,useHttpClient) 调用这个:
const useHttpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: "application/json" });
}
// add your own headers here
//options.headers.set("Access-Control-Allow-Origin", "true");
//const token = localStorage.getItem("token");
//const userName = authProvider.getAccount().userName;
//const [permissions, setPermissions] = useState();
//const permissions = useFetchPermissions(userName); throws error
//localStorage.setItem("permissions", permissions);
options.headers.set(
"Authorization",
`Bearer ${authProvider.getAccount().userName}`
);
return fetchUtils.fetchJson(url, options);
};