简体   繁体   English

尝试将更新的状态传递给组件时,如何修复未定义的 mapStateToProps?

[英]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我试图将 onClick 后的状态传递给组件
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 numOfCookies:当作为道具传递给 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.我为您在此处提供的代码创建了一个 stackblitz,它对我有用。 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包装您的应用程序正确传递您的商店

 <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.同样在声明动作类型(BUY_COOKIE 等)时,在单独的文件中声明动作类型,您可以将它们导入到减速器中。 You can declare action creators and action types in the same file if you want.如果需要,您可以在同一文件中声明动作创建者和动作类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM