happypoulp / redux-tutorial

Learn how to use redux step by step
3.76k stars 546 forks source link

Question for code: frozen: state._time.frozen #102

Closed alexQch closed 8 years ago

alexQch commented 8 years ago

Thanks for this great tutorial. It really makes learning Redux a lot more easier! I finished this but there is one part of the code I can't understand In file 11_src/src/home.jsx on line 109 to 118. which is:

const mapStateToProps = (state/*, props*/) => {
  return {
    frozen: state._time.frozen,
    time: state._time.time,
    // It is very bad practice to provide the full state like that (reduxState: state) and it is only done here
    // for you to see its stringified version in our page. More about that here:
    // https://github.com/rackt/react-redux/blob/v4.0.0/docs/api.md#inject-dispatch-and-every-field-in-the-global-state
    reduxState: state,
  }
}

Here, on line 3, in order to get the value of forzen and time why to we have to call _time function? Why can't we just do frozen: state.frozen ? Is it because we want that reducer be called first before we get these values? Any help will be appreciated!

happypoulp commented 8 years ago

Hi,

_time is not a function here, it's the name of the slice of our state in which the data we're interested in are located.

If you look at the state that is printed in the page of the example 11, it looks like this:

{
  "_time": {
    "frozen": false,
    "time": "19:41:20.489"
  }
}

So what happens in mapStateToProps is that we receive the state as shown above and we need to get the data out of _time property.

It's no coincidence though that the name of the slice in state is the same than the name of the reducer function _time. This is due to the way we constructed our store in 11_src/src/create-store.js. We got our reducers via import * as reducers from './reducers' which means that:

reducers={
  _time: function (state, action) {...}
}

Those reducers are combined into one reducer function thanks to combineReducers and in the end the state produced follow the same structure as the object passed to combineReducers (this is done by combineReducers for us). That's why since we passed a structure with _time key to combineReducers, our final state is also made of a structure with an _time key (and that's where the data returned by our _time reducer function are stored).

Is it more clear?

alexQch commented 8 years ago

Yes! Thanks!! This bit solve my confusion!

reducers={
  _time: function (state, action) {...}
}

Thanks again for this tutorial! Makes learning Redux much easier!