분명히 할 수있는 몇 가지 방법이 있습니다.
나는 아마 객체에 배열에서 당신의 국가 키를 확장합니다 :
이
{
active: {}
all: []
}
이제 all
에 대한 기존 감속기를 다시 사용할 수 있으며 active
에 대한 동작을 추가 :
const reducer = (state = {}, action) => {
switch (action.type) {
case UPDATE_LIST: // whatever action is currently updating your list
const nextAll = originalListReducer(state.all, action);
return {
active: nextAll[0],
all: nextAll
};
case NEXT_ACTIVE_ITEM:
const {active, all} = state;
const activeIndex = all.indexOf(active);
const nextIndex = (activeIndex + 1) % all.length;
return {
...state,
active: all[nextIndex]
};
default:
return state;
}
};
위의 originalListReducer
과 비슷하게 전화를 거는 자체 감속기로 active
상태를 관리하고 share the all
state by passing it as an additional argument을 만들 수도 있습니다. 다음과 같이하십시오 :
const reducer = (state = {}, action) => {
switch (action.type) {
case UPDATE_LIST: // whatever action is currently updating your list
const {all, active} = state;
const nextAll = originalListReducer(all, action);
const nextActive = nextActiveReducer(active, action, nextAll)
return {
all: nextAll,
active: nextActive
};
case NEXT_ACTIVE_ITEM:
const {all, active} = state;
return {
...state,
active: nextActiveReducer(active, action, all)
}
default:
return state;
}
};
const nextActiveReducer = (active, action, all) => {
switch (action.type) {
case UPDATE_LIST:
return all[0];
case NEXT_ACTIVE_ITEM:
return (all.indexOf(active) + 1) % all.length;
default:
return active;
}
};
당신이 할 수있는 또 다른 방법은 당신의 행동 창조자에게 논리를 밀어 넣는 것입니다.
const rootReducer = combineReducer({
all: allReducer,
active: activeReducer
});
const allReducer = (state = [], action) => {
switch (action.type) {
case UPDATE_LIST:
return action.list;
default:
return state;
}
};
const activeReducer = (state = null, action) => {
switch (action.type) {
case UPDATE_ACTIVE:
return action.nextActive;
default:
return state;
}
};
: 이제 감속기 이런
active
및
all
의 "바보"업데이터가 될
const nextActiveObject =() => {
return (dispatch, getState) => {
const {active, all} = getState();
const activeIndex = all.indexOf(active);
const nextIndex = (activeIndex + 1) % all.length;
const nextActive = all[nextIndex];
dispatch({ type: UPDATE_ACTIVE, active: nextActive });
}
};
:이 경우 현재 상태를보고 redux-thunk를 사용하고 적절한 "다음"활성 개체 작업을 전달할 수 있습니다
가고 싶은 분은 really up to you입니다.
목록의 마지막 항목에 도달하면 처음으로 돌아가서 첫 번째 요소를 다시 반환 하시겠습니까? 아니면 일단 끝나면 응용 프로그램에서 데이터를 표시하지 않습니까? –
일반적으로 redux 작업을 만드는 방법을 이해하는 것이 더 좋습니다. 어느 쪽이든 재미 있을지 모르지만 여기서 간단하고 명확하게 유지하려면 예라고 말하게하고 결국 끝나면됩니다. –
id가 아닌 인덱스를 추적해야합니다. 감속기를 다시 작성하여 2 가지 속성을 가진 객체를 반환하십시오. 하나는이 배열이고 다른 하나는 계속 클릭 할 때 업데이트되는 selectedIndex입니다. - 귀하의 요구 사항에 따라 selectedIndex는 처음에 0 또는 -1이됩니다. –