我在ReactJs和Redux购物车上工作。问题是,我添加到购物车的项目在购物车中未定义,并且没有显示
以下是添加到购物车的操作:
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,
}
})
)
}
}
推车减速器:
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
}
}
这是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)
)
}
}
如果我登录到控制台this.props.selecteditem
,则所有密钥都已定义。但如果我将一个项目添加到购物车并将其记录到控制台,则键是未定义的
你能告诉我怎么了吗
谢谢!
您不能在返回中生成mapStateToProps,这会导致错误你需要添加一个mapDispatchToProps来调度你的行动,在你的情况下;addToCart";行动你的代码会像一样
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)
**由于您发送了项目,因此无需在操作中对其进行销毁代码应该像这个
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,
}
})
)
}
}