【问题标题】:show components based on user role in react在反应中根据用户角色显示组件
【发布时间】: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


    【解决方案1】:
    1. 不要将数据从 reducer 状态复制到本地状态。必须保持单一事实来源
    2. 您已经拥有来自mapStateToPropsuserInfo,可以使用this.props.userInfo 在代码内部访问
    3. componentDidMount 内部调用 this.props.getUser() 而不从中获取任何东西,因为它会在你的减速器状态下稳定下来

    然后只需检查道具中的角色(来自状态机)并相应地渲染事物。如果您需要其他信息,我将在此答案下添加。 只是不要忘记添加保护子句以防止应用程序在实际数据仍未处于状态机中时崩溃。

    render() { if (!this.props.userInfo) return null . . .
    

    【讨论】:

    • 非常感谢。因为我是初学者,你能给我更多关于如何访问用户角色的信息吗?我的动作和减速器是否正确?
    • 这实际上取决于通过jwt_decode(localStorage.getItem('token'))构造的对象,您可以通过控制台记录它以查看它的结构。
    • 我怎样才能得到它?当我 console.log 我的 userInfo 我什么都没有得到......我的减速器和操作是否正确?
    • 我对 thunk 操作几乎没有经验,但 jwt 解码部分是否有效?你可以通过console.log里面的action来看看。我一直建议的最好的事情是使用 React Developer Tools chrome.google.com/webstore/detail/react-developer-tools/… 和 Redux DevTools chrome.google.com/webstore/detail/redux-devtools/…
    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多