【问题标题】:How do I use persist/rehydrate in redux-toolkit?如何在 redux-toolkit 中使用persist/rehydrate?
【发布时间】:2021-03-25 23:39:48
【问题描述】:

我已经按照文档中的建议使用 react-toolkit 设置了 redux-persist。现在我需要对补水进行一些操作,我该怎么做?这是我尝试过但不起作用的方法。

...
import { REHYDRATE } from 'redux-persist'
...

const accessControl = createSlice({
  name: 'accessControl',
  initialState,
  reducers: {
    loginStart(state: AccessControlState) {
      state.isLoading = true
    },
    loginSucces(state: AccessControlState, action: PayloadAction<LoginResponsePayload>) {
      state.isAuthenticated = true
      state.token = action.payload.access_token
      state.isLoading = false
      state.error = null
    },
    loginFailed(state: AccessControlState, action: PayloadAction<string>) {
      state.isAuthenticated = false
      state.token = ''
      state.isLoading = false
      state.error = action.payload
    },
    logout(state: AccessControlState) {
      state.isAuthenticated = false
      state.token = ''
      state.isLoading = false
      state.error = null
    },
    [REHYDRATE]: (state: AccessControlState) => {
      console.log('in rehydrate')
    }
  }
})

【问题讨论】:

    标签: typescript redux redux-toolkit redux-persist


    【解决方案1】:

    createSlice 使用reducers 对象的键来生成以切片名称为前缀的动作类型常量。在您的情况下,这些字符串是 accessControl/loginStartaccessControl/loginFailed

    没有调用您的 rehydrate reducer,因为它的操作类型常量扩展为 accessControl/persist/REHYDRATE,但 redux-persist 调度了一个类型为 persist/REHYDRATE 的操作。

    要处理再水化,您应该在 extraReducers 对象中编写减速器。这些 reducer 处理外部操作,不会在 slice 的 actions 属性中生成操作。

    例子:

    import { createSlice } from '@reduxjs/toolkit'
    import { REHYDRATE } from 'redux-persist'
    
    const accessControl = createSlice({
      name: 'accessControl',
      initialState,
      reducers: {
        ...
      },
      extraReducers: (builder) => {
        builder.addCase(REHYDRATE, (state) => {
          console.log('in rehydrate')
        });
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 2019-05-23
      • 2023-02-21
      • 2022-10-14
      • 2018-04-13
      • 2021-07-26
      • 1970-01-01
      • 2020-07-12
      相关资源
      最近更新 更多