gpt4 book ai didi

react-native - extraReducer 中的 redux-toolkit 状态更改不会启动重新渲染

转载 作者:行者123 更新时间:2023-12-02 19:30:27 26 4
gpt4 key购买 nike

我正在尝试同时注销和清除商店,所以点击我发送这个:

dispatch({type: PURGE, key: 'root', result: () => { } });

Redux persist 捕获它,并报告清除商店。伟大的。在另一个 reducer 中,我捕获了该调度,并像这样删除了我的访问 token :

import { PURGE } from 'redux-persist/es/constants';

const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
setAccessToken(state: AuthState, action: PayloadAction<Auth>): void {
state.accessToken = action.payload.accessToken;
state.expiresIn = action.payload.expiresIn;
},
},
extraReducers: {
[PURGE]: (state: AuthState, action: string): void => {
state.accessToken = initialState.accessToken;
state.expiresIn = initialState.expiresIn;
},
},
});

PURGE reducer 实际上被调用并修改了状态,但仍然没有重新渲染发生。所以 redux 不能接受它。但是根据文档,Redux 工具包使用 Proxy 对象作为状态并进行比较以查看它是否被修改。

我尝试过的事情:

state = initialState;

state = { ...initialState };

没用。存储工作,并保存数据,其他操作工作。我该如何继续?

编辑:进一步的调试显示我自己的 reducer 在 redux-persist reducer 之前被调用,并且 redux-logger 报告我的 reducer 根本没有改变状态。

最佳答案

我遇到了类似的问题(不是重新渲染),今天遇到了这个问题:似乎您无法完全替换状态对象。

发件人:https://redux-toolkit.js.org/usage/immer-reducers

Sometimes you may want to replace theentire existing state, either because you've loaded some new data, oryou want to reset the state back to its initial value.

WARNING A common mistake is to try assigning state = someValuedirectly. This will not work! This only points the local statevariable to a different reference. That is neither mutating theexisting state object/array in memory, nor returning an entirely newvalue, so Immer does not make any actual changes.

const initialState = []
const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
brokenTodosLoadedReducer(state, action) {
// ❌ ERROR: does not actually mutate or return anything new!
state = action.payload
},
fixedTodosLoadedReducer(state, action) {
// ✅ CORRECT: returns a new value to replace the old one
return action.payload
},
correctResetTodosReducer(state, action) {
// ✅ CORRECT: returns a new value to replace the old one
return initialState
},
},
})

所以

state = initialState;

会是

return initialState;

关于react-native - extraReducer 中的 redux-toolkit 状态更改不会启动重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61892626/

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