简体   繁体   English

如何使用 Immer 从减速器返回初始状态?

[英]How to return initial state from a reducer using Immer?

I am working on a React project and using Redux for state management.我正在开发一个 React 项目并使用 Redux 进行状态管理。 I'm moving from ImmutableJS to Immer, and I'm not sure how to return the initial state with some changes.我正在从 ImmutableJS 转移到 Immer,我不确定如何通过一些更改返回初始状态。 I was using merge from ImmutableJS, but not sure how to do it with Immer.我正在使用 ImmutableJS 的合并,但不确定如何使用 Immer。

I looked everywhere and couldn't find the answer.我到处找,找不到答案。 It seems like setting draft to initial state, and then making some changes doesn't work.似乎将草稿设置为初始状态,然后进行一些更改不起作用。

export const initialState = {
  initializedAuth: false,
  isAuthenticated: false,
  user: null,
};

const authProviderReducer = (state = initialState, action) =>
  produce(state, draft => {
    switch (action.type) {
      case AUTH_USER_NO_TOKEN:
        draft.initializedAuth = true;
        draft.isAuthenticated = false;
        break;

      case AUTH_UPDATE_USER_HAVE_TOKEN:
        draft.initializedAuth = true;
        draft.isAuthenticated = true;
        break;

      case AUTH_SUCCESSFUL_LOGIN:
        draft.initializedAuth = true;
        draft.isAuthenticated = true;
        draft.user = action.payload;
        delete draft.user.session;
        break;

      case AUTH_LOGOUT: {
        // return initialState;
        // draft = initialState; doesn't work
      }
    }
  });

On AUTH_LOGOUT , I want to return the initial state and set its initializedAuth property to true.AUTH_LOGOUT ,我想返回初始状态并将其initializedAuth属性设置为 true。

Using Immutablejs, I was able to do it like this:使用 Immutablejs,我可以这样做:

case AUTH_LOGOUT: {
    return initialState.set('initializedAuth', true);
}

It looks like you are following the correct pattern, except that your reducer's AUTH_LOGOUT case should work as follow:看起来您正在遵循正确的模式,除了您的减速器的AUTH_LOGOUT案例应该如下工作:

case AUTH_LOGOUT: {
    return draft[initializedAuth] = true;
}

About returning the intialState, there is this section in the docs:关于返回 intialState,文档中有这一节:

If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to produce:如果要使用此构造初始化未初始化的状态,可以通过将初始状态作为第二个参数传递来产生:

const byId = produce(
    (draft, action) => {
        switch (action.type) {
            .
            .
            .
        }
    },
    intialState <-- here
)

Reset draft to initialState and set initializedAuth . draft重置为initialState并设置initializedAuth

case AUTH_LOGOUT: {
  draft = initialState;         // reset to initialState
  draft.initializedAuth = true; // set to true

  break;
}
const appReducer = (state = initialState, action) =>
produce(state, draft => {
    switch (action.type) {
        case LOGOUT:
            return initialState;

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

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