Tylerlee12 Tylerlee12 - 3 months ago 72
Javascript Question

How is Redux passing state to mapStateToProps?

I'm trying to understand how React and Redux work, and I was looking at FuelSavingsPage.js from this example project. I get where

actions
comes from in
mapDispatchToProps
, but I don't understand how
state
is being passed to
mapStateToProps
or how
dispatch
is being passed to
mapDispatchToProps
. How is this happening?

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/fuelSavingsActions';
import FuelSavingsForm from '../components/FuelSavingsForm';

export const FuelSavingsPage = (props) => {
return (
<FuelSavingsForm
saveFuelSavings={props.actions.saveFuelSavings}
calculateFuelSavings={props.actions.calculateFuelSavings}
fuelSavings={props.fuelSavings}
/>
);
};

FuelSavingsPage.propTypes = {
actions: PropTypes.object.isRequired,
fuelSavings: PropTypes.object.isRequired
};

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

function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}

export default connect(
mapStateToProps,
mapDispatchToProps
)(FuelSavingsPage);

Answer

The React-Redux connect function generates a wrapper component that subscribes to the store. That wrapper component calls store.getState() after each dispatched action, calls the supplied mapStateToProps function with the current store state, and if necessary, calls mapDispatchToProps with the store's dispatch function.

Dan wrote a simplified version of connect a while back to illustrate the general approach it uses. See https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e .