- 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:
- Did you trigger CORRECT ACTION?
- Did you dispatched CORRECT ACTION TYPE?
- Do you have some async/await combined with TRY/CATCH and the errors are catched?
- Check the redux debug extension to see the diff of that action
- Then, possibly you changed the state DIRECTLY in reducer...
- Did you used shallow clone instead of deep clone in reducer?
- Spread operator will do shallow clone, did you use that?
Example
代码语言:javascript复制Common Mistakes when utilizing spread operator
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;
}