简体   繁体   中英

mapStateToProps and mapDispatchToProps is not sending props to component

Please I am working on a redux project but the data that was returned to mapStateToProps was not send to the component. Console.log props are undefined


LiveEvent.protoTypes = {
  event: PropTypes.object.isRequired,
  error: PropTypes.string,
};


const mapDispatchToProps = (dispatch) => { 
  return {
    getSingle: (values) => {
      console.log(Creators, "creators")
      dispatch(Creators.getOneEvent(values));
    },
  };
};

const mapStateToProps = (state) => (
  console.log(state.event.event, "state from liveEvent"),
  {
    event: state.event.event,
    error: state.event.error_message,
  }
);

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



function LiveEvent({match}, props) {
  console.log(props, "props")


Is there anything am not doing right

function LiveEvent({match}, props) {

The props object comes in the first argument to the function. Nothing is passed as the second argument. So you're destructuring the props to get match , and then creating a useless variable which is named props , but is unrelated to the actual props.

If you'd like to get the entire props object without destructuring, then change your code to:

function LiveEvent(props) {
// Do whatever with props, including things like 
//   const { match } = props
}

Alternatively, use destructuring to assign the props you care about to local variables:

function LiveEvent({ match, event, error, getSingle }) {

}

Ah, you have comma, I read it as semi-colon after console. It works fine.

There are miscellaneous bugs in your code.
  1. Console doesn't work here:

Implicit return

<LiveEvent event={...} error={...} />

To debug with the console, you have to use curly brace use return statement:

 const mapStateToProps = (state) => { console.log(state.event.event, "state from liveEvent"), return { event: state.event.event, error: state.event.error_message, } };
2. Defining proptypes in your component indicates that the component should pass the props.

Component props

LiveEvent.protoTypes = { event: PropTypes.object.isRequired, error: PropTypes.string, };

This code expects to have props in component itself:

 <LiveEvent event={...} error={...} />

The connected component with redux won't get props from it as it's first priority is to check and get props from the component itself.

So, remove proptypes from your component so that the component can receive redux props.

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