React reducer - data.map 不是函数或如何在 reducer 中向 case 添加值
React reducer - data.map is not a function or how to add values to case in a reducer
我有这个减速器:
export const reducer = ( state, { type, payload } ) => {
switch ( type ) {
case 'SET_TOURS_IN_CART':
return { ...state, toursInCart: payload };
default:
return state;
}
};
我想使用 SET_TOURS_IN_CART
分派将数据添加到这个减速器。
有效负载包含此数据:{id: '3', name: 'Best of Salzburg & Vienna in 8 Days Tour'}
我希望 toursInCart
包含一个对象数组,这样每次我添加新的有效负载时,该数组都会将新对象添加到现有数据中。
这是提供商:
import React, { useReducer, createContext } from 'react'
import { reducer } from './cart-context-reducer'
export const CartContext = createContext();
export default function CartContextProvider( props ) {
const initialState = {
toursInCart: []
},
[ data, dispatch ] = useReducer( reducer, initialState );
return (
<CartContext.Provider value={ { data, dispatch } }>
{ props.children }
</CartContext.Provider>
);
}
我做错了什么?
你 return 一个对象,而不是数组:return { ...state, toursInCart: payload };
(toursInCart: payload
部分)
如果要将 payload
添加到数组 toursInCart
,
尝试:
return {...state, toursInCart: [...state.toursInCart, payload]}
或任何变体
我有这个减速器:
export const reducer = ( state, { type, payload } ) => {
switch ( type ) {
case 'SET_TOURS_IN_CART':
return { ...state, toursInCart: payload };
default:
return state;
}
};
我想使用 SET_TOURS_IN_CART
分派将数据添加到这个减速器。
有效负载包含此数据:{id: '3', name: 'Best of Salzburg & Vienna in 8 Days Tour'}
我希望 toursInCart
包含一个对象数组,这样每次我添加新的有效负载时,该数组都会将新对象添加到现有数据中。
这是提供商:
import React, { useReducer, createContext } from 'react'
import { reducer } from './cart-context-reducer'
export const CartContext = createContext();
export default function CartContextProvider( props ) {
const initialState = {
toursInCart: []
},
[ data, dispatch ] = useReducer( reducer, initialState );
return (
<CartContext.Provider value={ { data, dispatch } }>
{ props.children }
</CartContext.Provider>
);
}
我做错了什么?
你 return 一个对象,而不是数组:return { ...state, toursInCart: payload };
(toursInCart: payload
部分)
如果要将 payload
添加到数组 toursInCart
,
尝试:
return {...state, toursInCart: [...state.toursInCart, payload]}
或任何变体