Peter89
Peter89

Reputation: 706

react, state change but not re-render

there is a case that I confused.

I have an object redux state: { show: true, creative: {name: 'a', tags: [t1, t2, t3] } }. This object have been mapped to props throught "connect" function of "react-redux".

When I change the attribute "show" or "creative.name", it does trigger re-render. But if I append t0 to "creative.tags", it does not run re-render.

# reducer.js
# block code does not re-render ===========
state.creative.tags.push(t0)
return state
# end block code does not re-render =======

I have to work around by assigning a new variable.

# reducer.js
# block code does re-render ===========
let new_state = Object.assign({}, state);
new_state.creative.dsp_tags.push(action.payload);
return new_state
# end block code does re-render =======

Could you please let me know how reactJS recognize the changed state?

Upvotes: 0

Views: 230

Answers (2)

bijayshrestha
bijayshrestha

Reputation: 149

Reducer by definition must consist of a or collection of Pure Functions. Meaning the ones where state must remain immutable. You can make a copy of your state object by using spread operation like ...state and then do the necessary operation.

Upvotes: 1

Ion
Ion

Reputation: 1292

You can't mutate the state directly, you should always create copy and return a new state. The fact that you are pushing directly into tags is whats causing the problem.

Create a new array instead before returning the state object:

const newtags = [...state.creative.tags, action.payload];
let creative= Object.assign({}, state.creative, { tags: newtags } );
let new_state = Object.assign({}, state, { creative } );

Upvotes: 4

Related Questions