简体   繁体   English

使用 redux-toolkit 将 state 重置为初始值

[英]Reset state to initial with redux-toolkit

I need to reset current state to initial state.我需要将当前 state 重置为初始 state。 But all my attempts were unsuccessful.但是我所有的尝试都没有成功。 How can I do it using redux-toolkit?我如何使用 redux-toolkit 来做到这一点?

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

Something like this:像这样的东西:

const intialState = {
  returned: []
}

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

This worked for me (mid-late 2020).这对我有用(2020 年中后期)。 Formatted with your code context as an example.以您的代码上下文为例进行格式化。

const initialState = {
  returned: [],
};

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

Replacing state with initialState directly did not work for me (mid 2020).更换stateinitialState直接没有为我工作(2020年年中)。 What I finally got working was to copy each property over with Object.assign() .我最终开始工作的是使用Object.assign()复制每个属性。 This worked:这有效:

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

In my case, as the previous answer, mid 2021, just setting the initial state DO NOT WORK, even if you use the toolkit adapter like :在我的情况下,如上一个答案,2021 年年中即使您使用工具包适配器,只需设置初始状态DO NOT WORK,如:

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


instead, you should use Object.assign() , guess that it's related with the internal immer library behavior相反,您应该使用Object.assign() ,猜测它与内部 immer 库行为有关

We do it like this guys.我们就是这样的人。

Suppose you want to clear all the data at the point of logging out.假设您要在注销时清除所有数据。

In your store.tsx file:在您的 store.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,
});

Then you create a thunk like this:然后你创建一个这样的thunk:

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

You can use spread opearator for initialState您可以使用传播opearator的initialState

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

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

@i9or i have a similar question, but for combined slices, I want to able to reset the state to default when i call the log @i9or 我有类似的问题,但是对于组合切片,我希望能够在调用日志时将 state 重置为默认值

code for combining reducers alongside reduxtoolkit-query将 reducer 与 reduxtoolkit-query 结合使用的代码

 // 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 });

When using multiple slices, all slices can be reverted to their initial state using extraReducers .当使用多个切片时,所有切片都可以使用 extraReducers 恢复到它们的初始state

First, create an action that can be used by all slices:首先,创建一个可以被所有切片使用的动作:

export const revertAll = createAction('REVERT_ALL')

In every slice add an initialState , and an extraReducers reducer using the revertAll action:在每个切片中添加一个initialState和一个使用revertAll操作的extraReducers减速器:

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

The store can be created as usual:可以照常创建商店:

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

And in your react code you can call the revertAll action with the useDispatch hook:在您的反应代码中,您可以使用useDispatch挂钩调用revertAll操作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM