简体   繁体   中英

State mutation in Redux

I know that Reducers are just pure functions that take the previous state and an action, and return a new state objects, instead of mutating the previous state.
But although direct mutations are not Redux's philosophy, it's still possible (or i missed something) :

 const reducer = (oldState = initialState, action) => { switch (action.type) { case "ACT": { // mutate state directly instead of create a new one oldState.subobj.ssub.key = "hi hi"; return oldState; } default: { return oldState; } } }; 

Full code here

Why does not redux perform verification to prevent this kind of action ?
How can we ensure that developers will never do that ?

Redux can't make such verification, because it doesn't know if new data for certain action should actually update the state. Redux use reducers, because it doesn't know how to update your state. It is your business logic, therefore you must provide such state transitions.

Redux is comparing object references, which is fast. If it would do some kind of duplicate state tree and compare objects recursively, it would introduce performance penalties.

To make sure that your developers are not doing it, I guess your best bet is to establish good development discipline, unit test your reducers, use deep-freeze library in these tests, and enforce deep-freeze usage in code reviews.

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.

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