首页 > 解决方案 > 将 React 组件渲染为变量时,如何从 mapStateToProps 访问变量?

问题描述

我有一个组件,我试图从中访问状态,它看起来像这样:

const Product = ({add, id, title, image}) => (
  <div className={styles.product} onClick={() => add(id)}>
    <img src={image} alt={title} className={styles.productImage}/>
    {title}
  </div>
);

export default connect(() => ({}), {add})(Product);

我添加了 MapStateToProps,现在看起来像这样:

const Product = ({add, id, title, image}) => (
  <div className={styles.product} onClick={() => add(id)}>
    <img src={image} alt={title} className={styles.productImage}/>
    {title}
    {items.length}
  </div>
);

const mapStateToProps = (state) => {
  return {
    items: state.cart.items,
  };
};

export default connect(mapStateToProps, {add})(Product);

使用上面的代码,我进入items is not defined了我的控制台。然而,当删除{items.length}和使用 React 开发工具时,我可以看到 Product 组件可以访问items. 如何items从组件中读取此变量?

标签: javascriptreactjsreact-redux

解决方案


这种解构 props 参数的设计模式非常不规范

const Product = ({add, id, title, image}) => (

我建议不要这样做,因为它会使您的代码难以调试。你不能 console.log 你的 props 参数来尝试调试问题。此外,任何阅读您的代码的人都会感到困惑,因为他们不会看到它。

const Product = (props) => (
   <div className={styles.product} onClick={() => add(props.id)}>
       <img src={props.image} alt={props.title} className={styles.productImage}/>
       {props.title}
       {props.items.length}
   </div>
);

如果这不起作用,则您的操作或减速器可能有问题。因此,您需要先添加 console.logs

const Product = (props) => {
   console.log(props)
   return (
       <div className={styles.product} onClick={() => add(props.id)}>
           <img src={props.image} alt={props.title} className={styles.productImage}/>
           {props.title}
          {props.items.length}
       </div>
   )
};

const mapStateToProps = (state) => {
    console.log(state);
    return {
       items: state.cart.items,
    };
};

推荐阅读