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

Zir*_*ael 24 javascript redux redux-toolkit

我需要将当前状态重置为初始状态。但我所有的尝试都没有成功。我如何使用 redux-toolkit 做到这一点?

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

Run Code Online (Sandbox Code Playgroud)

i9o*_*9or 38

像这样的东西:

const intialState = {
  returned: []
}

const showOnReviewSlice = createSlice({
    name: 'showOnReview',
    initialState,
    reducers: {
        reset: state => initialState
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,它有效。同样正确的是reset(){return initialState}或reset:()=>initialState (7认同)
  • @Dorklord `state = initialState` 不起作用,因为您正在更改引用,而 redux 工具包无法知道这一点,因为它保留了旧引用。您必须**要么**改变原始的“状态”**或***返回*新对象。@nachtigal @fullStackChris (6认同)
  • 我认为只需设置“state = initialState”就足够了,因为在其他示例中,我们只需要改变“state”。唉,重置状态需要不同的方法:/ (5认同)
  • 我必须管理,即使 redux-toolkit 也很棒,它是一点点不变性 dark-magic :D Btw `return { ...initialState }` 也有效...... (2认同)
  • @Baterka `return { ...initialState }` 是不必要的,也许您来自禁止突变的传统 redux。这里 `return initialState` 和 `return { ...initialState }` 是等价的。 (2认同)

Ble*_*lee 21

当使用多个切片时,可以使用extraReducers将所有切片恢复到其初始状态。

首先,创建一个可供所有切片使用的操作:

export const revertAll = createAction('REVERT_ALL')
Run Code Online (Sandbox Code Playgroud)

在每个切片中添加一个initialState, 和一个extraReducers减速器,使用以下revertAll操作:

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

可以像往常一样创建商店:

export const store = configureStore({
  reducer: {
    someReducer: someSlice.reducer,
  }
})
Run Code Online (Sandbox Code Playgroud)

在您的反应代码中,您可以revertAll使用钩子调用该操作useDispatch

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

  return <span onClick={() => dispatch(revertAll())}>Reset</span>
}
Run Code Online (Sandbox Code Playgroud)

  • 哇!这就是我一直在寻找的! (3认同)

Fre*_*Ben 13

state直接替换为对我来说不起作用initialState(2020 年中)。我最终要做的就是用 复制每个属性。这有效:Object.assign()

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


Gil*_*oot 9

我们就像这些人那样做。

假设您想在注销时清除所有数据。

在您的 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,
});

Run Code Online (Sandbox Code Playgroud)

然后你创建一个像这样的thunk:

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

发送注销 thunk 后,您还可以刷新浏览器,以便它自动将用户重定向到登录页面。

function MyReactComponent() {
   const dispatch = useDispatch()

   function myLogoutOnClickHandler() {
      dispatch(logout())
      window.location = window.location;
   }
   ...

}
Run Code Online (Sandbox Code Playgroud)


小智 7

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

const initialState = {
  returned: [],
};

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

Run Code Online (Sandbox Code Playgroud)


Fra*_*mon 6

就我而言,正如之前的答案(2021 年中期),仅设置初始状态是行不通的,即使您使用如下工具包适配器:

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


Run Code Online (Sandbox Code Playgroud)

相反,你应该使用Object.assign(),猜测它与内部沉浸库行为有关