简体   繁体   中英

what is state parameter in mapStateToProps in React-Redux

I am a beginner to React-Redux. I want to understand the state parameter in mapStateToProps(state) . Should we consider state our component state or Reducer State ? I really need to understand the behind-the-scenes of Redux.

Code

function mapStateToProps(state) {
  return {
    course: state.course
  };
}

So here is the answer

state inside the mapStateToProps gets all the state of store So let say you have these

books:[{
}],
chairs:{
  ...
},
table:{}

these 3 states in store mapStateToProps will have all of these states, so to use a specific state in component you can extract that from state variable passed to mapStateToProps

In your case you need just course state in your component so you are getting that only

Let me know if you need more explanation

I mean should we consider state as our component local state or we referring this state as Reducer State

Per the Redux docs , the state argument contains the entire Redux Store state.

The first argument to a mapStateToProps function is the entire Redux store state (the same value returned by a call to store.getState()).

Redux is basically a state management tool, there you have a centralized store , which basically is similar to you component state but different because here its not only component specific data, its application wide data. Where you components can access this store to get them the piece of data they need.

function mapStateToProps acts just as its name suggests, it maps out store data to our component props, that is how you get the data from the redux store, via props. So in your case,

I suppose your store object is something like this,

{ course : { courseId : 'A' , courseName : 'Maths' ...} }

what you are doing in mapStateToProps is, mapping your store data to component props, so the state passed to mapStateToProps is actually the store

function mapStateToProps(state) {
  return {
    course: state.course
  };
}

state which is passed to mapStateToProps as your first argument, is your entire redux store that consists of different pieces of states from your reducers. As listed in redux Docs

The first argument to a mapStateToProps function is the entire Redux store state (the same value returned by a call to store.getState()). Because of this, the first argument is traditionally just called state. (While you can give the argument any name you want, calling it store would be incorrect - it's the "state value", not the "store instance".)

The mapStateToProps function should always be written with at least state passed in.

Hope this helps !

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