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

raa*_*rts 2 react-native react-redux redux-toolkit

我试图同时注销并清除商店,因此单击我会发送以下内容:

dispatch({type: PURGE, key: 'root', result: () => { } });
Run Code Online (Sandbox Code Playgroud)

Redux persist 捕获它,并报告清除存储。伟大的。在另一个减速器中,我捕获该调度,并删除我的访问令牌,如下所示:

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;
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

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

我尝试过的事情:

state = initialState;
Run Code Online (Sandbox Code Playgroud)

state = { ...initialState };
Run Code Online (Sandbox Code Playgroud)

没用。商店可以工作,可以保存数据,其他操作也可以工作。我该如何继续?

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

小智 5

我面临着类似的问题(不是重新渲染),今天遇到了这个线程:\n似乎你不能完全替换状态对象。

\n

来自: https: //redux-toolkit.js.org/usage/immer-reducers

\n
\n

有时您可能想要替换\n整个现有状态,因为您已经加载了一些新数据,或者\n您想要将状态重置回其初始值。

\n

警告 一个常见的错误是尝试直接分配 state = someValue\n。这是行不通的!这仅将本地状态变量指向不同的引用。这既不会改变内存中现有的状态对象/数组,也不会返回全新的值,因此 Immer 不会进行任何实际更改。

\n
\n
const initialState = []\nconst todosSlice = createSlice({\n  name: \'todos\',\n  initialState,\n  reducers: {\n    brokenTodosLoadedReducer(state, action) {\n      // \xe2\x9d\x8c ERROR: does not actually mutate or return anything new!\n      state = action.payload\n    },\n    fixedTodosLoadedReducer(state, action) {\n      // \xe2\x9c\x85 CORRECT: returns a new value to replace the old one\n      return action.payload\n    },\n    correctResetTodosReducer(state, action) {\n      // \xe2\x9c\x85 CORRECT: returns a new value to replace the old one\n      return initialState\n    },\n  },\n})\n
Run Code Online (Sandbox Code Playgroud)\n

所以

\n
state = initialState;\n
Run Code Online (Sandbox Code Playgroud)\n

将会

\n
return initialState;\n
Run Code Online (Sandbox Code Playgroud)\n