【发布时间】:2020-09-12 06:48:19
【问题描述】:
我正在编写应用程序,但我无法解决问题。我已经在 state 中存储了用户信息(当我打开 Redux DevTools 时,我可以看到 state -> user: {username: name, role: ...})。
现在在某些组件中,我想检查登录用户是管理员还是用户。我有它处于那种状态,但我怎样才能在某个类中加载它?当我导出一个函数时,我可以使用const userRole = useSelector(state => state.security.user.role_id);,但在一个类中它会产生问题。你能帮助我吗?
这是我的 User 类代码,我想显示 DELETE 按钮,前提是用户是管理员:
import React, {Component} from "react";
import PropTypes from "prop-types";
import {connect, useSelector} from "react-redux";
import { Link } from "react-router-dom";
import { deleteUser } from "../../store/actions/userActions";
class User extends Component{
constructor() {
super();}
onDeleteClick(id) {
this.props.deleteUser(id);
}
render() {
const { user } = this.props;
return (
<div className='row entry'>
<div className='col-sm-2'>
<span >{user.username}</span>
</div>
<div className='col-sm-2'>
<span >{user.name}</span>
</div>
<div className='col-sm-2'>
<span>{user.lastname}</span>
</div>
<div className='col-sm-2'>
<span>{user.tag}</span>
</div>
<div className='col-sm-1'>
<span>{user.pay}</span>
</div>
<div className='col-sm-1'>
<span>
{user.role_id}
</span>
</div>
<div className='col-sm-2'>
<Link to={`userlist/edituser:${user.id}`}>
<button><i className="fas fa-user-edit"></i></button>
</Link> | <button onClick={this.onDeleteClick.bind(this, user.id)}><i className="far fa-trash-alt"></i></button>
</div>
</div>
)
}
}
User.propTypes = {
deleteUser: PropTypes.func.isRequired
};
export default connect(
null, { deleteUser }
)(User);
【问题讨论】:
-
你的问题不清楚。是什么造成了问题?
-
你应该使用 Redux 的 connect() 来连接你的组件和 store Redux,你做到了吗?
-
我已经编辑了问题