我有我的初始状态:
export default function DrinkCalculator(state = initialState, action) {
let payload = action.payload;
switch (action.type) {
case UPDATE_DRINKS_CALCULATOR:
return [{
...state,
...payload
}];
case ADD_DRINK:
let newState= [Object.assign({},state)];
newState.push(action.payload);
return newState;
如何添加到我的数组来保存一个对象数组?我如何更改我的reducer以将对象添加到数组中,这样我就可以存储大量条目而不只是一条。
我希望我的州成为:
[{
drinkType: 5,
drinkVolume: 4,
drinkStrength: 5,
drinkQuantity: 5,
drinkStength: 5
},
{
drinkType: 1,
drinkVolume: 2,
drinkStrength: 2,
drinkQuantity: 5,
drinkStength: 7
},
{
drinkType: 3,
drinkVolume: 5,
drinkStrength: 2,
drinkQuantity: 5,
drinkStength: 5
},
{
drinkType: 5,
drinkVolume: 5,
drinkStrength: 5,
drinkQuantity: 5,
drinkStength: 5
}
]
更新:我将嵌套对象复制到我的状态,我想获得顶级属性并将它们作为对象添加到数组中。
当我在这里解雇时:
onClick() {
const drinkQuantity = this.state.counter;
const drinks = this.props.DrinksCalculator;
if (!drinkQuantity) {
this.props.dispatch(showError());
} else {
this.props.dispatch(updateDrinksCalculator({drinkQuantity}));
// fire addDrink to copy drinks props in new object
this.props.dispatch(addDrink( drinks ));
this.props.router.push('/calc/5');
}
}
答案 0 :(得分:1)
如果我理解你,你想为你的州添加一个新属性。
const initialState = {
drinkType: null,
drinkVolume: null,
drinkStrength: null,
drinkQuantity: null,
drinkStength: null
};
const someReducer=(state=initialState,action) => {
switch (action.type) {
case "SOME_ACTION":{
let newState= Object.assign({},state,{newAttribute:["value1","value2"]});
return newState;
}
}
这将创建一个具有newAttribute属性的状态。
我个人喜欢列出我将在initialState中使用的所有属性。对于阅读代码的人来说,它将更容易使用他们将要使用的属性以及其中的数据。
将对象推入数组的另一个例子
dispatch({
type:"ADD_QUESTIONS",
question:{
drinkType: 5,
drinkVolume: 4,
drinkStrength: 5,
drinkQuantity: 5,
drinkStength: 5
}
})
const initialState = {
questions:[]
};
const someReducer=(state=initialState,action) => {
switch (action.type) {
case "ADD_QUESTIONS":{
let newState= Object.assign({},state);
newState.questions.push(action.question);
return newState;
}
}