javascript - 将 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
从组件中读取此变量?
解决方案
这种解构 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,
};
};
推荐阅读
- javascript - Javascript 集中的项目重复
- java - 如何在 Main 方法中调用将数组作为参数的方法?
- constraints - pyeda 方法“抽象语法树”
- python - 从列表python类中的每个项目中获取2个项目
- git - git:从已推送到功能分支的远程删除不需要的文件
- python-3.x - 通过 pytest 运行时,日志记录模块无法创建文件
- c# - 无法通过 Navigation.pushasync 与 xamarin 中的 collectionview 传递绑定上下文
- unity3d - 我的游戏似乎没有按正确的顺序播放场景
- java - 为什么当 Data 实现 Comparator 接口时,编译器会抱怨构造带有不可比较元素的排序集合?
- powerbi - 根据另一列中的字符串添加自定义列