redux - 填充数组然后重置的操作

时间:2017-04-15 11:56:43

标签: arrays redux

我正在尝试填充一个小数组[应该有两个元素]。初始状态是

selected: []

一旦填充了2个插槽[a,b],它应该比较数字是否相等(返回true或false)并将数组重置为原始状态[]。

export const selectTile = (idx) => {
  return {
    type: SELECT_TILE,
    idx
  };
};


const initialState = {
  selected: [],
  matched: 0,
  score: 0
};

export default (state = initialState, action) => {
  switch (action.type) {
    case SELECT_TILE:
      return { ...state, selected: state.selected.push(action.idx) };
    default:
      return state;
  }
};

我已经偶然发现了第一个问题。上面的reducer返回错误" state.selected.push不是函数'。

当调度第一个动作时,它应该执行:

  1. 检查阵列的长度是否小于2
  2. 如果是,请将元素推送到数组:

    已选择:[x]

  3. 另一个动作:

    1. 检查阵列的长度是否小于2
    2. 是的,将元素推送到数组:

      选择:[x,y]

    3. 另一个动作:

      1. 检查阵列的长度是否小于2
      2. no - 比较x === y,(返回某事,例如真或假或任何旗帜)
      3. 无论是否x === y,重置'选择'数组到[]并等待另一个动作。
      4. 编辑:

        我认为上面的描述不准确(顺便说一下,点击一个瓷砖就会调出一个动作):

          

        行动1:[x]

             

        动作2:[x,y](如果x = y,匹配:真,选中:[])

             

        动作3:[x](发送此动作的那一刻,它应该清除   选中'数组和一个新元素应该添加到数组中。   正如下面的答案所示,第三个动作只是清除了   数组,但没有添加新元素。

        我已经调整了下面的答案,但它给出了一个错误,即state.slice不是一个动作(当我第二次点击一个磁贴时出现错误(动作2被调度)。

        case SELECT_TILE:
              if (state.selected.length < 1) {
                    return { ...state, selected: [...state.selected, action.idx] };
              } else if (state.selected.length === 1) {
                    const nextState = state.slice();
                    nextState.selected.concat(action.idx);
                    if (nextState.selected[0] === nextState.selected[1]) {
                      return { ...nextState, score: nextState.score + 1, selected: [] };
                    }
                    return { ...nextState, selected: [] };
              }
        

1 个答案:

答案 0 :(得分:1)

您必须使用concat在重新调整项目时将项目推送到状态数组

export default (state = initialState, action) => {
  switch (action.type) {
    case SELECT_TILE:
      return { ...state, selected: state.selected.concat(action.idx) };
    default:
      return state;
  }
};

或者您可以使用传播运营商本身,我认为这是一种更好的方式

  return { ...state, selected: [...state.selected, action.idx] };

根据您的要求被视为

export default (state = initialState, action) => {
  switch (action.type) {
    case SELECT_TILE:
      if(state.selected.length < 2) {
            return { ...state, selected: [...state.selected, action.idx] };
      } else {
           if(state.selected[0] === state.selected[1]) {
                return {...state, matched: true, selected: []}
           }
      }

    default:
      return state;
  }
};