我得到:
TypeError:无法读取未定义的属性“ concat”
但是,我已经在initialState
中定义了“订单”数组。
有人知道原因吗?
import * as actionTypes from '../actions/actionTypes.js';
import { updateObject } from '../utility.js';
const initialState = {
orders: [],
loading: false,
purchased: false
};
const purchaseInit = (state, action) => {
return updateObject(state, { purchased: false });
};
const purchaseBurgerStart = (state, action) => {
return updateObject(state, { loading: true });
};
const purchaseBurgerSuccess = (state, action) => {
const newOrder = updateObject(action.orderData, { id: action.orderId });
return updateObject(state, {
loading: false,
purchased: true,
orders: state.orders.concat(newOrder)
});
};
const purchaseBurgerFail = (state, action) => {
return updateObject(state, { loading: false });
};
const fetchOrdersStart = (state, action) => {
return updateObject(state, { loading: true });
};
const fetchOrdersSuccess = (state, action) => {
return updateObject(state, {
orders: action.orders,
loading: false
});
};
const fetchOrdersFail = (state, action) => {
return updateObject(state, { loading: false });
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.PURCHASE_INIT: return purchaseInit(state, action);
case actionTypes.PURCHASE_BURGER_START: return purchaseBurgerStart(state, action);
case actionTypes.PURCHASE_BURGER_SUCCESS: return purchaseBurgerSuccess(state, action);
case actionTypes.PURCHASE_BURGER_FAIL: return purchaseBurgerFail(state, action);
case actionTypes.FETCH_ORDERS_START: return fetchOrdersStart(state, action);
case actionTypes.FETCH_ORDERS_SUCCESS: return fetchOrdersSuccess(state, action);
case actionTypes.FETCH_ORDERS_FAIL: return fetchOrdersFail(state, action);
default: return { state };
}
};
export default reducer;
答案 0 :(得分:0)
1)此行...
case actionTypes.PURCHASE_BURGER_SUCCESS: return purchaseBurgerSuccess(state, action);
...与该switch
语句中的所有其他行一样,应该返回新状态。
因此在purchaseBurgerSucess
中,您需要确保使用要传递的状态作为参数来返回新状态:
const purchaseBurgerSuccess = (state, action) => {
const newOrder = updateObject(action.orderData, { id: action.orderId });
// Spread out the state you pass in as an argument
// and update those properties that have changed
return {
...state,
loading: false,
purchased: true,
orders: state.orders.concat(newOrder)
};
};
注意:您的其他功能也属于此陷阱,因此也需要对其进行更新。
2)您的default
语句中的switch
案应为:
default: return state;
答案 1 :(得分:0)
请检查state参数,此参数没有状态数组,您可以使用console.log来检查此参数具有什么内容。
答案 2 :(得分:0)
我认为您缺少在参数中将状态分配为初始状态。
const PurchaseBurgerSuccess =(状态= initialState,操作)