使用redux-toolkit将状态重置为初始状态

1hdlvixo  于 2022-11-12  发布在  其他
关注(0)|答案(8)|浏览(186)

我需要将当前状态重置为初始状态。但是我的所有尝试都不成功。我如何使用redux-toolkit来做这件事?

const showOnReviewSlice = createSlice({
  name: 'showOnReview',
  initialState: {
    returned: [],
  },
  reducers: {
    reset(state) {
      //here I need to reset state of current slice
    },
  },
});
pkbketx9

pkbketx91#

大概是这样的:

const intialState = {
  returned: []
}

const showOnReviewSlice = createSlice({
    name: 'showOnReview',
    initialState,
    reducers: {
        reset: () => initialState
    }
});
kmynzznz

kmynzznz2#

这对我很有效(2020年中晚期)。以您的代码上下文为例进行格式化。

const initialState = {
  returned: [],
};

const showOnReviewSlice = createSlice({
  name: 'showOnReview',
  initialState,
  reducers: {
    reset: () => initialState,
  },
});
q9rjltbz

q9rjltbz3#

直接用initialState替换state对我来说 * 不 * 起作用(2020年中期)。我最后得到的工作是用Object.assign()复制每个属性。这工作:

const showOnReviewSlice = createSlice({
    name: 'showOnReview',
    initialState: {
        returned: []
    },
    reducers: {
        reset(state) {
            Object.assign(state, initialState)
        }
    }
});
64jmpszr

64jmpszr4#

在我的情况下,正如前面的答案,2021年中期,只需设置初始状态**不工作,**即使您使用工具包适配器,如:

reducers: {
        // Other reducers
         state = tasksAdapter.getInitialState({
                status: 'idle',
                error: null,
                current: null
            })
        }
    },

相反,您应该使用Object.assign(),猜测它与内部immer库行为相关

qni6mghb

qni6mghb5#

当使用多个切片时,可以使用extraReducers将所有切片恢复到其初始状态。
首先,创建一个可供所有切片使用的动作:

export const revertAll = createAction('REVERT_ALL')

在每个切片中添加一个initialState,并使用revertAll操作添加一个extraReducers缩减器:

const initialState = {};
export const someSlice = createSlice({
  name: 'something',
  initialState,
  extraReducers: (builder) => builder.addCase(revertAll, () => initialState),
  reducers: {}
});

可以照常创建存储区:

export const store = configureStore({
  reducer: {
    someReducer: someSlice.reducer,
  }
})

在react代码中,可以使用useDispatch钩子调用revertAll操作:

export function SomeComponent() {
  const dispatch = useDispatch();

  return <span onClick={() => dispatch(revertAll())}>Reset</span>
}
acruukt9

acruukt96#

我们要这样做。
假设您要在注销时清除所有数据。
在您的商店.tsx文件中:

import { AnyAction, combineReducers, configureStore } from '@reduxjs/toolkit';
import authReducer from './slices/authSlice'
import messageReducer from './slices/messageSlice'

const appReducer = combineReducers({
  auth: authReducer,
  message: messageReducer,
});

const reducerProxy = (state: any, action: AnyAction) => {
  if(action.type === 'logout/LOGOUT') {
    return appReducer(undefined, action);
  }
  return appReducer(state, action);
}

export const store = configureStore({
  reducer: reducerProxy,
});

然后创建如下形式的thunk:

export const logout = createAsyncThunk(
    "auth/logout",
    async function (_payload, thunkAPI) {
        thunkAPI.dispatch({ type: 'logout/LOGOUT' });
        console.log('logged out')
    }
);
0kjbasz6

0kjbasz67#

您可以对initialState使用跨页运算符

const initialState: {
  returned: unknown[] //set your type here
} = {
  returned: []
}

const showOnReviewSlice = createSlice({
  name: 'showOnReview',
  initialState,
  reducers: {
    reset() {
      return {
        ...initialState
      }
    }
  }
});
oiopk7p5

oiopk7p58#

@i9或者我也有类似的问题,但是对于组合切片,我希望在调用日志时能够将状态重置为默认值
用于将reduxtoolkit-query与reducer组合在一起的代码

// combining the reducers
const reducers = combineReducers({
  // regular-state
  themeMode: themeSlice.reducer,
  user: userSlice.reducer,
  onboarding: onboardingSlice.reducer,
  setupWizard: setupWizardSlice.reducer,
  // end regular-state
  //start rtk-query
  [supplyMgtApi.reducerPath]: supplyMgtApi.reducer,
  [vendorApi.reducerPath]: vendorApi.reducer,
  [warehouseApi.reducerPath]: warehouseApi.reducer,
  [inventoryApi.reducerPath]: inventoryApi.reducer,
  [commonsApi.reducerPath]: commonsApi.reducer,
  [productApi.reducerPath]: productApi.reducer,
  [employeeApi.reducerPath]: employeeApi.reducer,
  [payGroupApi.reducerPath]: payGroupApi.reducer,
  [rolesApi.reducerPath]: rolesApi.reducer,
  [taxationApi.reducerPath]: taxationApi.reducer,
  //end rtk-query
});

相关问题