简体   繁体   中英

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?

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)

  1. state here in mapStateToProps means state in ReduxStore .

  2. It maps Redux state to ReactComponent props . It's not necessarily to map props to states, eg Pure Component

mapStateToProps pass state as a props to component using react-redux connect () function. Consider connect() function as wrapper component, which passes props to children.

                    mapStateToProps
connect (state) ----------------------->  component(props)

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