【发布时间】:2021-03-10 00:28:38
【问题描述】:
我目前正在构建亚马逊克隆,但在将商品添加到购物车时尝试更新我的 Redux 商店时遇到了一些问题。当我像这样对我的操作进行硬编码时
// src/redux/actionCreators.js
export const addToCart = () => ({
type: "ADD_TO_CART",
item: {
id: 1,
title: "book",
image: "hi",
price: 420,
rating: 3,
}
})
该项目已添加到我的 redux 商店。但是,我想在我的操作创建器中使用我的产品组件中的道具作为 id、标题、图像、价格和评级值。
// src/components/Product.js
import React from 'react';
import '../Product.css';
import { connect } from 'react-redux';
import { addToCart } from '../redux/actionCreators'
const Product = (props) => {
return (
<div className="product">
<div className="product__info">
<p>{props.title}</p>
<p className="product__price">
<small>$</small>
<strong>{props.price}</strong>
</p>
<div className="product__rating">
{Array(props.rating)
.fill()
.map((_, i) => (
<p>⭐️</p>
))}
</div>
</div>
<img src={props.image} alt={props.title}/>
<button onClick={ props.addToCart }>Add To Cart</button>
</div>
)
}
const mapStateToProps = (state) => ({ cart: state.cart.cart })
export default connect(mapStateToProps, { addToCart })(Product)
这样我的操作看起来像这样
// src/redux/actionCreators.js
export const addToCart = (props) => ({
type: "ADD_TO_CART",
item: {
id: props.id,
title: props.title,
image: props.image,
price: props.price,
rating: props.rating,
}
})
但是,道具是未定义的。直接通过动作传递道具将不起作用,那么将我的产品组件道具与动作创建者一起使用的正确方法是什么?
【问题讨论】:
标签: javascript reactjs redux react-redux