Redux-DOM not refreshed

2022-09-21 10:26:41 浏览数 (2)

  • Why My DOM not refreshed?

  • Example
  • Best Practise

Why My DOM not refreshed?

We all know that if state changed then DOM will refresh, if we dispatched an action but the DOM not refreshed, definitely you triggered side effect.

Here is a debug checklist:

  1. Did you trigger CORRECT ACTION?
  2. Did you dispatched CORRECT ACTION TYPE?
  3. Do you have some async/await combined with TRY/CATCH and the errors are catched?
  4. Check the redux debug extension to see the diff of that action
  5. Then, possibly you changed the state DIRECTLY in reducer...
    1. Did you used shallow clone instead of deep clone in reducer?
    2. Spread operator will do shallow clone, did you use that?

Example

Common Mistakes when utilizing spread operator

代码语言:javascript复制
const rv = (state === undefined) ? defaultState : { ...state };
switch (action.type) {
  case LOGIN_ERROR:
    /* 
        Spread Operator only do shallow copy here
    the grand child are still referenced to state

    that means: after spread operator, rv.loginPage.msg === state.loginPage.msg
    */
  /* YOU ARE CHANGING STATE DIRECTLY  */
    rv.loginPage.msg = {
      ...state.loginPage.msg,
      ...action.data,
    }
    return rv;
}

Best Practise

代码语言:javascript复制
const rv = (state === undefined) ? defaultState : { ...state };
switch (action.type) {
  case LOGIN_ERROR:

    /*
    spread the object for each generation 
    */
    rv.loginPage = {
      ...state.loginPage, /* we spreaded the child */
      msg: {
        ...state.loginPage.msg, /* we spreaded the grandchild */
        ...action.data,
      },
    };
        
    return rv;
}

0 人点赞