gpt4 book ai didi

typescript - 我如何在 redux-toolkit 中使用 persist/rehydrate?

转载 作者:行者123 更新时间:2023-12-05 01:32:49 25 4
gpt4 key购买 nike

我已经按照文档中的建议使用 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')
}
}
})

最佳答案

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

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

要处理再水合,您应该改为在 extraReducers 中编写您的 reducer 目的。这些 reducer 处理外部操作,不会在切片的 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')
});
}
})

关于typescript - 我如何在 redux-toolkit 中使用 persist/rehydrate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65304153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com