2017-04-06 130 views
0

我有一个状态,其中的一部分是一个名为'数字'的数组。其中一个动作是以下面的方式改变状态:所有的奇数应该被改为零,所有的偶数都应该被保留。例如:react-native redux - reducer改变数组元素

previous state 
[9, 3, 2, 6, 8] 

action 
new state 
[0, 0, 2, 6, 8] 

行动的创建者:

export const turnEven =() => { 
    return { 
    type: TURN_EVEN 
    }; 
}; 

减速机:

case TURN_EVEN: 
     return [...state, numbers: state.numbers.map(
     (i) => (i % 2 === 0 ? i : 0))]; 

这其中产生一个错误:意外的标记,预计, ......而 '回归' 路线正在被指示为错误的位置。 请告知

回答

2

望着那你共享代码:

case TURN_EVEN: 
     return [...state, numbers: state.numbers.map(
     (i) => (i % 2 === 0 ? i : 0))]; 

它看起来像这样减速的状态下具有不同的特性,其和为numbers之一。

也许你想要做这个:

case TURN_EVEN: 
    return Object.assign(
    {}, 
    state, 
    { numbers: state.numbers.map(i => (i % 2 === 0 ? i : 0)) } 
); 

我还没有看到你减速的休息,所以也许我没有足够的背景,但我会鼓励你尽量使减速对于该州的每个属性,其中一个numbers,然后使用combineReducers to combine them into one。小函数更容易处理。

如果你这样做,那么你可以有这样一个对数字的减速机:

const initialState = []; 
const numbersReducer = (state = initialState, action) => { 
    swicth (action.type) { 
    case TURN_EVEN: 
     return state.map(i => (i % 2 === 0 ? i : 0)); 
    // Other action types here... 
    default: 
     return state; 
    } 
} 
+1

谢谢。我实际上使用了联合收割机,并为州的“数字”属性设置了一个单独的缩减器。上面的例子工作正常。谢谢。 – Wasteland