[英]React and Redux Shopping cart, add to cart action
I am working at a ReactJs and Redux shopping cart.我在 ReactJs 和 Redux 购物车工作。 The problem is that the item which I add to cart it is as undefined in the cart and it is not displayed.问题是我添加到购物车中的商品在购物车中未定义并且未显示。
Here is the action for add to cart:这是添加到购物车的操作:
export const addToCart = ( { item }) => {
return (dispatch) => {
return (
dispatch({
type: ADD_TO_CART,
payload:
{ id: item?.id,
name: item?.name,
brand: item?.brand,
quantity: item?.quantity,
}
})
)
}
}
Cart reducer:推车减速机:
const initialState = {
cart: [],
}
export default function addToCartReducer(state=initialState, action) {
switch(action.type){
case ADD_TO_CART:
return {
...state,
cart:[...state.cart, {
id: action.payload.id,
name: action.payload.name,
brand: action.payload.brand,
quantity: action.payload.quantity
}]
};
default:
return state
}
}
And this a fragment of MyComponent:这是 MyComponent 的一个片段:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addToCart } from '../Actions/actions'
export class MyComponent extends Component {
render(){
return(
<section>
<button onClick = {()=>this.props.addToCart(this.props.selectedItem)}
ADD TO CART
</button>
</section>
const mapStateToProps = (state) => {
return {
selectedItem: filterAttributesSelector(state),
}
}
export default connect(mapStateToProps, {addToCart})(MyComponent)
)
}
}
If I log to the console this.props.selecteditem
all the keys are defined.如果我登录到控制台this.props.selecteditem
定义了所有键。 But if I add an item to cart and log it to the console the keys are undefined.但是,如果我将一个项目添加到购物车并将其记录到控制台,则键是未定义的。
Could you please tell me what it is wrong?你能告诉我这是怎么回事吗?
Thank you !谢谢 !
You cannot make mapStateToProps in your return, it should cause errors You need to add a mapDispatchToProps to dispatch your actions in your case the "addToCart " action.您不能在退货中制作 mapStateToProps,它应该会导致错误您需要添加一个 mapDispatchToProps 以在您的情况下调度您的操作“addToCart”操作。 your code will be like that你的代码会是这样的
import React, { Component } from 'react' import { connect } from 'react-redux' import { addToCart } from '../Actions/actions' export class MyComponent extends Component { render(){ return( <section> <button onClick={()=>this.props.addToCart(this.props.selectedItem)}> ADD TO CART </button> </section> ) } } const mapStateToProps = (state) => { return { selectedItem: filterAttributesSelector(state), } } const mapDispatchToProps = (dispatch) => { return { addToCart: (item) => dispatch(addToCart(item)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
** Since you send the item so no need to destruct it in your action code should be like this ** 由于您发送了该项目,因此无需在您的操作代码中销毁它应该是这样的
export const addToCart = (item) => { return (dispatch) => { return ( dispatch({ type: ADD_TO_CART, payload: { id: item?.id, name: item?.name, brand: item?.brand, quantity: item?.quantity, } }) ) } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.