是否可以从 redux-toolkit 中的另一个动作分派 slice 的动作?

Is it okay to dispatch slice's action from another action in redux-toolkit?

我正在使用 redux-toolkit 并且有 2 个部分:“auth”和“profile”

auth => 处理令牌信息
配置文件 => 处理有关用户帐户的信息

当用户尝试登录时,我向 api 发送请求,returns 向我发送用户令牌和帐户信息。然后我需要保存这些信息。我把令牌放到相应的字段(在同一个切片中)。我需要将我的帐户信息放入“配置文件”切片(登录处理发生在“auth”切片中)。现在我只是从 'auth' slice.

调度 setProfile 操作

从“auth”分派分派“profile”动作是反模式吗? 或者我必须将这个逻辑从 redux 移动到组件? 或者在切片之外进行“登录”操作? 还是我需要将它们全部放在一片中?

// PROFILE SLICE | profile.js 

const initialState = {
  data: {},
  status: 'idle'
}

export const profileSlice = createSlice({
  name: 'profile',
  initialState,
  reducers: {
    setProfile(s, {payload: profile}) {
      s.profile = profile
    }
  }
})

export const {setProfile} = userSlice.actions;
export default profileSlice.reducer


// AUTH SLICE | auth.js

import {setProfile} from './profile' // import action creator from profile slice

const initialState = {
  token: null,
  status: 'idle'
}

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setToken(s, {payload: token}) {
      s.token = token
    }
  }
})

export const login = ({email, password}) => dispatch => {
  return api.auth.login({
    email,
    password
  })
    .then(res => {
      const {token, ...profile} = res.data
      dispatch(setToken(token))
      dispatch(setProfile(profile)
    })
}

export const {setToken} = authSlice.actions;
export default authSlice.reducer

你不能在 slice/reducer 内部调度动作,尽管你当然可以从 thunk 中的任何地方调度动作。

但是,您可以监听 任何其他 reducer 中的另一个切片的操作,事实上,这是我们鼓励的模式:

这样做时要注意的一件事是,如果两个不同的切片相互依赖,您最终可能会遇到“循环导入依赖”问题,在这种情况下,您需要提取一些通用功能为了打破进口周期:

https://redux-toolkit.js.org/usage/usage-guide#exporting-and-using-slices

在这种特定情况下,我看到您实际上是将 token 值从其余数据中分离出来。我建议分派一个 single 操作,其中包含所有接收到的登录数据,并让两个 slice reducer 挑选出他们关心的部分。