【问题标题】:Is it okay to dispatch slice's action from another action in redux-toolkit?可以从 redux-toolkit 中的另一个动作调度 slice 的动作吗?
【发布时间】:2021-07-15 19:40:53
【问题描述】:

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

auth => 处理有关令牌的信息
profile => 处理有关用户帐户的信息

当用户尝试登录时,我向 api 发送请求,它返回用户令牌和帐户信息。然后我需要保存这些信息。我将令牌放入相应的字段(在同一切片中)。而且我需要将我的帐户信息放入“profile”切片(登录处理发生在“auth”切片中)。现在我只是从 'auth' 切片中调度 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

【问题讨论】:

  • 您的选择很少。 - 从您的成功处理程序发送另一个操作。或者您可以编写中间件(或使用一些中间件)来观察操作并在处理您的成功身份验证操作时分派另一个。

标签: javascript reactjs redux redux-toolkit


【解决方案1】:

您不能在切片/reducer 内分派操作,尽管您当然可以从 thunk 中分派操作,无论它是在哪里编写的。

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

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

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

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

【讨论】:

  • 但是我必须把这个动作放在哪里?为“常见”操作创建一些切片?
  • 或者我是否需要在 root reducer 中添加一些 thunk,将其命名为“login”,然后从“auth”和“profile”reducer 中调度操作?
  • 再次抱歉,我只是对redux有点经验,我还有一个变种。也许我可以在 root reducer (dispatch(initUser)) 中发送 thunk。然后,在这个 thunk 中,调度操作 (dispatch("userInited")) 以及所有需要的信息。从'auth'和'profile'减速器我必须听这个动作?这样对吗?对我来说,这个选项看起来最方便
猜你喜欢
  • 2021-05-05
  • 2022-11-22
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 2017-07-14
  • 2020-04-23
相关资源
最近更新 更多