我有一个具有不同功能的MERN应用程序。因此,许多角色和功能需要显示特定的数据、nav选项和特定角色的div,并对其他角色进行隐藏。请记住,我不想隐藏整个组件,而只是组件的一部分。我已经保护了后端,但不确定如何停止显示特定的components.Where,如果我保存角色(用户信息),这样我就不必一次又一次地调用API。
就像这里,您可以看到我是如何调用api来获取用户信息的。
try{
const data=await axios.post(
"http://localhost:5000/api/auth/role",
_id,
config
);
if(data.role=="admin"){
delete DRoutes[0].children[0].children[2];
console.log(DRoutes[0].children[0].children[2]);
}
}
我不想重复这个过程(调用api ),每次我需要用户信息。
发布于 2022-10-18 02:32:12
这是上下文的经典用例之一。您有一个上下文提供程序,它包含有关当前登录用户的信息,并且由(可能)主应用程序组件更新。然后,在其余的组件中,需要了解用户的组件将是上下文使用者。有关示例,请参阅文档,但下面是一个草图:
const { useState, useContext } = React;
const UserContext = React.createContext(
null // No user is logged in yet
);
const PlainComponent = () => {
return <div className="boxed">This component doesn't care about the user context</div>;
};
const UserAwareComponent = () => {
const userContext = useContext(UserContext);
const haveUser = userContext !== null;
// You could use userContext?.hasNiftyAccess here, but sadly SO's
// version of Babel is so out of date it doesn't know about
// optional chaining
const userHasNiftyAccess = userContext && userContext.hasNiftyAccess;
return (
<div className="boxed">
This one does:
{haveUser && <div>We have a user</div>}
{!haveUser && <div>No user logged in</div>}
{userHasNiftyAccess && <div>User with nifty access is logged in</div>}
</div>
);
};
const BlockCheckbox = ({ text, checked, update, disabled = false }) => {
const onClick =
update &&
(({ currentTarget: { checked } }) => {
update(checked);
});
return (
<div>
<label>
{text}
<input type="checkbox" disabled={disabled} checked={checked} onClick={onClick} />
</label>
</div>
);
};
const App = () => {
const [userLoggedIn, setUserLoggedIn] = useState(false);
const [userHasNiftyAccess, setUserHasNiftyAccess] = useState(false);
const userContext = userLoggedIn ? (userHasNiftyAccess ? { hasNiftyAccess: true } : {}) : null;
return (
<UserContext.Provider value={userContext}>
<BlockCheckbox text="User Logged In?" value={userLoggedIn} update={setUserLoggedIn} />
<BlockCheckbox
text="User Has Nifty Access?"
value={userHasNiftyAccess}
update={setUserHasNiftyAccess}
disabled={!userLoggedIn}
/>
<hr />
<PlainComponent />
<UserAwareComponent />
</UserContext.Provider>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
.boxed {
border: 1px solid black;
padding: 4px;
margin: 4px;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
https://stackoverflow.com/questions/74109445
复制相似问题