gpt4 book ai didi

javascript - 将 React 组件渲染为变量时,如何从 mapStateToProps 访问变量?

转载 作者:行者123 更新时间:2023-11-30 20:06:41 25 4
gpt4 key购买 nike

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

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>
);

如果这不起作用,则您的操作或 reducer 可能有问题。因此,您需要先添加 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 - 将 React 组件渲染为变量时,如何从 mapStateToProps 访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52848467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com