简体   繁体   中英

How to dispatch an array from a Reducer

This is my reducer code,

export default function homeReducer(state = {}, action){
  switch(action.type){
    case types.GET_USER_DATA_SUCCESS:
      return Object.assign({}, state, action.user);

    case types.GET_MEDIA_FOR_USER_SUCCESS:
      return Object.assign({}, state, action.medias);

    default:
      return state;


  }
}

Now user is an object by medias is an array of object.

Now when I pass medias to my component,

function mapStateToProps(state, ownProps){
  return {
    user: state.home,
    medias: state.home
  };
}

I get a validation error, against this code,

HomePage.propTypes = {

  user : PropTypes.object.isRequired,
  medias: PropTypes.array.isRequired
};

Warning: Failed propType: Invalid prop `medias` of type `object` supplied to `HomePage`, expected `array`. Check the render method of `Connect(HomePage)`.

I can't seem to understand what I'm doing wrong here.

Try changing

Object.assign({}, array) 

To

 [...array]

try this...

export default function homeReducer(state = { user: {}, media: [] }, action){
  switch(action.type){
    case types.GET_USER_DATA_SUCCESS:
      return Object.assign({}, state, { user: action.user });

    case types.GET_MEDIA_FOR_USER_SUCCESS:
      return Object.assign({}, state, { media: action.medias });

    default:
      return state;
  }
}

Then...

function mapStateToProps(state, ownProps){
  return {
    user: state.home.user,
    medias: state.home.media
  };
}

Just make sure your action.medias is indeed an array.

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