1

I have two container components in my app. I just started react, redux and thought that a container component gets state object from its respective reducer so that it can be mapped to the component's props.

I console logged the state sent by the reducer and saw that the state object contains the data sent by the other reducer in my app as well. I thought it's supposed to get data only from its corresponding reducer because the reducer is what sends data to a container component.

I don't know if I'm doing something wrong or if that's how it is.

The reducer:

    export default function(state=null, action){
    console.log(action);
    switch(action.type){
        case 'BOOK_SELECTED':
            return action.payload
    }
    return state;
}

The container component:

    function mapStateToProps(state){
     console.log("state from reducer",state); //contains data from the other reducer as well
    return {
        bookDetail : state.bookDetail
    }
}

export default connect(mapStateToProps)(BookDetail);
  • what do you mean by "its respective reducer"? what are you expecting links a container to a specific reducer? – azium Dec 15 '17 at 07:20

2 Answers2

1

Containers and reducers are not "connected". That's why mapStateToProps exists.

Redux doesn't know what parts of the state a container needs, so, in mapStateToProps, all the state is provided and each one takes whatever it needs. In your case, your container needs state.bookDetail.

Hope it helps.

Héctor
  • 24,444
  • 35
  • 132
  • 243
0

If you check react-redux documentation, you'll see that mapStateToProps receives the full store data as first argument. It's your job to slice that to the props needed by the connected component, as you are already doing. Your component will only receive bookDetail as a prop from the state.

So your code is fine, although I would rewrite that switch statement in the reducer with a default clause.

Mauricio Pasquier Juan
  • 2,265
  • 3
  • 27
  • 39