I am having a problem with a react component not re-rendering even though I see the state being properly updated. I am using redux, I have read state mutation is often the issue/cause of this I just dont think I am doing that. The value I am updating is nested 3 levels deep within the state.
Here is the code:
import { RECEIVE_CURRENT_SCAN_RESULT } from '../constants';
const initialState = {
currentScanResult: {info:{}, results:[]},
};
[RECEIVE_CURRENT_SCAN_RESULT]: (state, payload) =>
Object.assign({}, state, {
currentScanResult: Object.assign(state.currentScanResult, payload)
}),
export function createReducer(initialState, reducerMap) {
return (state = initialState, action) => {
const reducer = reducerMap[action.type];
return reducer
? reducer(state, action.payload)
: state;
}
}
In Object.assign
the first argument is the "target" object,
so this line
currentScanResult: Object.assign(state.currentScanResult, payload)
is still mutating the currentScanResult
property on the state.
Use an empty object as first argument in Object.assign
, like you did on the first level, so the whole thing becomes:
// empty object as target here
Object.assign({}, state, {
// empty object as target here as well
currentScanResult: Object.assign({}, state.currentScanResult, payload)
})
and that should at least test if the the problem is a problem of mutation or if there is something else that needs fixing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.