Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable component using React Redux mapStateToProps

A React component OilBarrel connected my redux store to create a container OilBarrelContainer:

// ---- component

class OilBarrel extends Component {
  render() {
     let data = this.props.data;
     ...
  }
}

// ---- container

function mapStateToProps(state) {
  let data = state.oilbarrel.data;
  ...
}

const OilBarrelContainer = connect(mapStateToProps)(OilBarrel)

// ---- reducer

const oilbarrel = (state = {}, action) => {
  let data = state.data;
}

const storeFactory = (server = false, initialState = {}) => {
    return applyMiddleware(...middleware(server))(createStore)(
        combineReducers({oilbarrel, otherReducer1, otherReducer2}),
        initialState
    )
}

I find it strange that mapStateToProps() receives the top level state object (the entire state of the application), requiring me to traverse state.oilbarrel.data, when the reducer (conveniently) only receives the branch of the state that belongs to this component.

This limits the ability to reuse this container without knowing where it fits into the state hierarchy. Am I doing something wrong that my mapStateToProps() is receiving the full state?

like image 529
Eric Petroelje Avatar asked Aug 15 '26 14:08

Eric Petroelje


1 Answers

That is the mapStateToProps behavior. You have to think redux state as a single source of truth (by the way, that is what it really is) independently of the components you have in project. There is no way out, you have to know the exactly hierarchy of you especific data in the state to pass it to your container component.

like image 91
Henrique Oecksler Bertoldi Avatar answered Aug 17 '26 04:08

Henrique Oecksler Bertoldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!