Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux with React-Native and mapStateToProps

I've read this thread. What is the difference between state and props in React?

It says that props are different from states and ideally props should not be change in its component and only should be changed by its parent component.

However, mapStateToProps function in react-redux maps states in Redux to props of a React components, which is basically changing props of a React component when Redux state is changed by an Redux action.

It does not make sense to me. It seems that it should have been mapStateToStates instead and maps Redux states to states of a React component.

Am I missing something?

like image 703
gpminsuk Avatar asked Jan 03 '17 07:01

gpminsuk


1 Answers

It says that props are different from states and ideally props should not be change in its component and only should be changed by its parent component.

State here refers to the internal state of the component, which the component can change internally via .setState().

However, mapStateToProps function in react-redux maps states in Redux to props of a React components, which is basically changing props of a React component when Redux state is changed by an Redux action.

The state here refers to the redux store, an external state. react-redux's connect method creates a HOC - higher order component (a component which is aware of the store's state changes). The HOC wraps the dumb react component, which is not aware of the store. Using mapStateToProps the HOC maps the data from the external state, and inject it to the react component via the props.

State in redux store -> mapStateToProps in HOC -> props passed to the dumb component

So the HOC is the parent, and the dumb component is the child. The parent injects new props to the child component, and the 1st assertion "props should not be change in its component and only should be changed by its parent component" is not violated.


Notes:

  1. More info about higher order component can be found in Dan Abramov's article about Presentational and Container Components.

  2. To understand how react-redux connect works - in the online free course, Getting Started with Redux, Dan Abramov shows how to build connect from scratch (lessons 22-29)

like image 186
Ori Drori Avatar answered Oct 19 '22 06:10

Ori Drori