How is state immutability actually used in Redux?

感情迁移 提交于 2020-01-14 19:23:49

问题


I am trying to understand how immutability is actually (if at all) used in Redux. Every tutorial/article/document I found states that reducers should never alter the state object but instead create a new copy of the changed data (i.e. the reducers must be pure functions). I understand this but I could not find any place where there is an explanation of how this guideline is actually used by Redux internal implementation.

Is this just a strong recomendation or will something inside Redux breaks if I make the reducers non pure?

If it is the later then what exactly will break?

I did find several places where Dan says that in some (very rare) cases the reducers may be non pure but it is risky (again, with no explanation what is the risk exactly).


回答1:


Redux, when used with React, is typically connected by using connect from react-redux. Wrapping a component with connect, makes it subscribe to changes to the redux store by specifying a change handler, which gets invoked after an action is dispatched and the reducers are called. Upon invocation of the change handler, connect compares the current state of the store with the new state using identity comparison (previousState !== newState) – which is faster than doing a shallow or deep comparison – and only when the two states aren't identical, does it update the wrapped component using setState. Mutating the state directly will not cause the references to change, thereby causing the wrapped component to not re-render.

This is how connect determines if it should call setState:

if (!pure || prevStoreState !== storeState) {
  this.hasStoreStateChanged = true
  this.setState({ storeState })
}

connect also provides an option to override this behaviour by specifying that the wrapped component is not pure using:

connect(mapStateToProps, mapDispatchToProps, mergeProps, {pure: false} )

Identity comparison is also used by pure components by implementing shouldComponentUpdate to prevent unnecessary calls to render.

TL;DR: a component wrapped with connect will not re-render if a store's state changes due to mutation.

Edit: Nothing in Redux itself will break since it is so minimal that it doesn't try to inspect the state returned by reducers.



来源:https://stackoverflow.com/questions/35970515/how-is-state-immutability-actually-used-in-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!