简体   繁体   中英

How to fix mapStateToProps is undefined when trying to pass updated state to component?

I am trying to pass the state after onClick to the component
but it does not display because it is undefined. I want to display the state as the remaining number of cookies for sale

class CookieContainer extends Component {
  render(){
  return (
    <div className="donutShop" >
    //below I want to pass the updated state but {this.props.numOfCookies} is undefined
      <h2>Cookies available for Sale: {this.props.numOfCookies}</h2>
      <button onClick={this.props.buyCookie}>Buy cookie</button>
    </div>
  );
};
}

numOfCookies: is undefined when passed as props to CookieContainer

const mapStateToProps = state => ({numOfCookies: state.numOfCookies})
// dispatch
const mapDispatchToProps = dispatch => {
  return {
    buyCookie: () => dispatch(buyCookie())
  };
};

let ConnectedCookie = connect(mapStateToProps, mapDispatchToProps)(CookieContainer)

export default ConnectedCookie

// action
export const buyCookie = () => {
  return {
    type: BUY_COOKIE,
    content: 1
  };
};


// state
const initialCookieState = {
    numOfCookies: 100
}


const BUY_COOKIE = "BUY_COOKIE";
//reducer
const cookieReducer = (state = initialCookieState, action) => {
  switch (action.type) {
    case BUY_COOKIE:
      return {
        ...state,
        numOfCookies: state.numOfCookies - action.content
      };
    default:
      return state;
  }
};

I have created a stackblitz for the code that you provided here and it is working for me. The code itself seems fine. The problem might be in what you have not shown in your question. Make sure that you have created your store

const store = createStore(cookieReducer);

and passed your store properly by wrapping your app with provider

 <Provider store={store}>
    <App />
 </Provider>

Also when declaring action types(BUY_COOKIE, etc.), declare the action types in a separate file and you can import them in the reducer. You can declare action creators and action types in the same file if you want.

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