我正在尝试填充一个小数组[应该有两个元素]。初始状态是
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不是函数'。
当调度第一个动作时,它应该执行:
如果是,请将元素推送到数组:
已选择:[x]
另一个动作:
是的,将元素推送到数组:
选择:[x,y]
另一个动作:
编辑:
我认为上面的描述不准确(顺便说一下,点击一个瓷砖就会调出一个动作):
行动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: [] };
}
答案 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;
}
};