繁体   English   中英

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

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

我试图将 onClick 后的状态传递给组件
但它不显示,因为它是未定义的。 我想将状态显示为待售饼干的剩余数量

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:当作为道具传递给 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;
  }
};

我为您在此处提供的代码创建了一个 stackblitz,它对我有用。 代码本身看起来不错。 问题可能出在您未在问题中显示的内容中。 确保您已创建商店

const store = createStore(cookieReducer);

并通过使用provider包装您的应用程序正确传递您的商店

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

同样在声明动作类型(BUY_COOKIE 等)时,在单独的文件中声明动作类型,您可以将它们导入到减速器中。 如果需要,您可以在同一文件中声明动作创建者和动作类型。

暂无
暂无

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

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