如何检查什么类型的用户目前登录在我的反应应用程序?使用redux工具箱进行状态管理



所以我正在React中构建一个HR应用程序,我目前需要做的是检查登录的用户类型,以便有条件地呈现该类型的用户可以看到的内容。我不知道在这里要实现什么逻辑。我知道我必须声明一个函数并将其命名为useEffect,但我不知道如何开始。下面我将粘贴我的redux用户切片:

export interface AuthUser {
id: number
name: string
roles: Array<'admin' | 'group_admin' | 'employee'>
teams?: string[]
token?: string
}
xport const authSlice = createSlice({
name: 'auth',
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
addTeam: ({ user }, action: PayloadAction<string>) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
user = user
? {
...user,
teams: user.teams ? [...user.teams, action.payload] : [action.payload]
}
: null
},
logout: (state) => {
state.user = null
}
},
// The `extraReducers` field lets the slice handle actions defined elsewhere,
// including actions generated by createAsyncThunk or in other slices.
extraReducers: (builder) => {
builder
.addCase(login.pending, (state) => {
state.status = 'loading'
})
.addCase(login.fulfilled, (state, action) => {
state.status = 'idle'
state.validationErrors = []
localStorage.setItem('token', action.payload?.token ?? '')
state.user = action.payload
})
.addCase(login.rejected, (state, action) => {
state.status = 'empty'
state.validationErrors = action.payload as ValidationMessage[]
})
}
})

我需要在我的导航栏内实现我的逻辑,我认为这对我来说是不相关的。任何关于如何开始的帮助都是可以接受的,提前感谢

我认为你的用户应该有一个role属性,在那里他将有一个<'admin' | 'group_admin' | 'employee'>值,目前看来,你在用户中有一个角色数组。

首先,让用户在登录后从后台接收一些角色,然后通过选择器获得这个用户对象或用户角色,然后有条件地呈现你需要的任何东西,如:

{user.role === ROLES.admin ? <AdminComponent /> : <SomeOtherComponent />}

{user.role === ROLES.admin && <AdminComponent />}

或者以任何其他方式,这只是几个例子

最新更新