我正在创建一个可以添加项目的购物车,我的Add_To_Cart操作正在运行,但REMOVE_FROM_CART没有做任何事情。我的预感是减速器没有做正确的事情。这是我的代码:
Cart.js(容器):
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { RemoveFromCart } from '../actions/remove_from_cart';
class Cart extends Component {
constructor(props){
super(props);
this.renderQuantity = this.renderQuantity.bind(this)
}
renderTotal(){
const { cart } = this.props;
let sum = 0;
return (
<div>
${cart.total}
</div>
)
}
renderQuantity(){
const { cart, RemoveFromCart } = this.props;
return (
<div>
{Object.keys(cart.quantityPerId).map(function(key){
return <li key={key}>
item: {key} ||
Quantity: {cart.quantityPerId[key]} ||
<button
onClick={() => RemoveFromCart(key, cart.quantityPerId[key])}
>Return
</button></li>;
})}
</div>
)
}
render() {
return (
<div>
<h3>Cart</h3>
Total:
{this.renderTotal()}
Quantity per Item:
{this.renderQuantity()}
</div>
);
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators({ RemoveFromCart }, dispatch);
}
function mapStateToProps(state) {
return { itemList: state.itemList, cart: state.cart }
}
export default connect(mapStateToProps,mapDispatchToProps)(Cart);
remove_from_cart.js(动作创作者)
export const REMOVE_FROM_CART = 'REMOVE_FROM_CART';
export function RemoveFromCart(name, quantity) {
return {
type: REMOVE_FROM_CART,
name,
quantity
};
}
reducer_cart.js(reducer)
import { ADD_TO_CART } from '../actions/add_to_cart';
import { REMOVE_FROM_LIST } from '../actions/remove_from_list';
const initialState = {
total: 0,
quantityPerId: {}
}
const total = (state = initialState.total, action) => {
switch (action.type) {
case ADD_TO_CART:
if (parseInt(action.quantity) > 0 ) {
return state += parseInt(action.price)
}
}
}
const quantityPerId = (state = initialState.quantityPerId, action) => {
switch(action.type) {
case ADD_TO_CART:
if (parseInt(action.quantity) > 0) {
return {...state, [action.name] : (state[action.name] || 0) + 1
}
}
case REMOVE_FROM_CART:
Object.keys(quantityPerId).map(function(name){
if (action.name === name && parseInt(action.quantity) > 0) {
// return Object.assign({}, name, { name: action.quantity - 1})
return {...state, name : state[action.name] - 1}
}
})
default:
return state
}
}
const cart = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
return {...state,
total: total(state.total, action),
quantityPerId: quantityPerId(state.quantityPerId, action)
}
default:
return state
}
}
export default cart
同样,问题在于REMOVE_FROM_CART。
答案 0 :(得分:1)
你没有回到那里:
case REMOVE_FROM_CART: {
Object.assign()..... //but not return statement?
}
通过redux docs,每个reducer都需要始终返回新的状态。尝试返回您的点差,看看会发生什么。
case REMOVE_FROM_CART: {
return Object.assign... //returning spread
}
答案 1 :(得分:0)
将reducer导入商店时,导入的代码位于cart
函数中,该函数不包含REMOVE_FROM_CART
个案例...
此文件外的任何人都不知道total
函数。因此,在处理REMOVE_FROM_CART
操作时,cart
缩减器无法识别并将其处理为&#39;默认&#39;。
由于两者都处理相同的状态对象,因此需要定义一个包含两者的函数。