我需要一些帮助,或者想知道这是否可能。。
如果只有当前用户具有管理员权限,我希望显示按钮。
在我的redux状态中,有一个isAdministrator属性,如果当前用户具有isAdministrator:true,那么我想显示按钮。
return (
<div>
{userInfo ? (
<Link id="OpenUserManagament" to="/userManagement">
<Button style={{ marginLeft: 10, marginBottom: 6 }} size="lg">
User Management
</Button>
</Link>
):(
<Nav.Link></Nav.Link>
)}
</div>
)
所以在userInfo之后。。那是我的州信息
const userLogin = useSelector((state) => state.userLogin);
const { userInfo } = userLogin;
{loading: true, userInfo: {…}}
loading: true
userInfo:
auth: {username: 'admin', password: '********'}
isAdministrator: true
token: {}
userID: "admin"
userName: "admin"
_id: ""
[[Prototype]]: Object
[[Prototype]]: Object
您提出的问题是可能的。但从您的代码中,我无法理解您的userLogin对象是什么样子的。你可以尝试console.log,这样你就可以看到里面有什么。
一旦你解决了这个问题,你就需要把你的代码包装在一个div中,如下所示:
//here is component body
return (
<div>
{userInfo.userId === "admin" ?? (
<Link id="OpenUserManagament" to="/userManagement">
<Button style={{ marginLeft: 10, marginBottom: 6 }} size="lg">
User Management
</Button>
</Link>
)}
</div>
)
如果你能整理出userInfo ,它应该会起作用
一个简单的三进制就可以了。。。
// Just a dummy example...
function AdminButton({ userInfo }) {
return (
<div>
{userInfo.isAdministrator ? (
<React.Fragment>
<p>hello admin here's some links and blah blah blah</p>
<button onClick={() => alert('yay!!')}>Hello, admin!</button>
</React.Fragment>
) : null}
</div>
);
}
ReactDOM.render(<AdminButton userInfo={{ isAdministrator: true }} />, root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<h1>Welcome! If you see a button below, you are the admin</h1>
<div id="root"></div>
我刚刚使用了null
,如果用户不是演示的管理员,它将不显示任何内容。你可以用类似的东西显示其他东西:
(/* ... */) : (
<Nav.Link></Nav.Link>
)