【发布时间】:2021-11-09 22:11:37
【问题描述】:
我想显示一个组件,它是基于用户角色的图标,我正在使用 react/redux,但我不知道该怎么做。我必须为此获取解码的用户令牌。 组件privateRoute:
<PrivateRoute path="/settings" component={waitFor(Settings)} />
和我的行动:
export const getUser = () => {
if (localStorage.getItem('token')) {
return jwt_decode(localStorage.getItem('token'))
}}
export const getUserInfo = (userData)=>dispatch=>{
const userData = jwt_decode(localStorage.getItem('token'))
dispatch({
type: userConstants.GET_USER_DATA,
payload : userData
})}
这是我的减速器:
const initState = {
userData: {
},
};
const userReducers = (state = initState, action) => {
switch (action.type) {
case userConstants:
return null;
case userConstants.GET_USER_DATA:
return {
...state,
userData: action.payload
}
default:
return state
}}
我想在这个侧边栏组件中有图标:
class Sidebar extends Component {
constructor(props) {
super(props)
this.state = {
userRoles: [],
listItems: [
{
listText: 'setting',
listIcon: SettingIcon,
expan: true,
isExpanded: false,
route: '',
key: "Setting",
///otheritems...
],
}
}
componentDidMount() {
let userData = this.props.getUser();
if (userData && userData.role) {
this.setState({ userRoles: userData.role })
}
}
}
render(){
return(
<div>{{this.state.listItems.map((item, index) => {
let flag = true;
if (item.key === 'Setting' && this.state.userRoles.length &&
!this.state.userRoles
.map((rol) => rol)
.includes("Admin")
) {
flag = false;}if(flag){
<img src={item.listIcon} />
}}
</div>)}
const mapStateToProps = state => {
return {
openSideBar: state.openSideBar ,
userInfo : state.userInfo
};};
const mapDispatchToProps = (dispatch) => ({
logout: () => dispatch(logout()),
getUser: () => getUser(),
getUserInfo : () => dispatch(getUserInfo())
});
我已经重新编写了代码,所以请不要介意语法
【问题讨论】:
标签: reactjs authentication redux jwt token