我有一个使用Redux的React应用程序,目前有3个reducer-Event,Attendee,Locations。我们将采取行动来添加/修改/删除所有3个reducer。
到目前为止很好。
现在的问题是,我有许多UI状态,例如-showAddEventPopup,ShowEditEventPopup,isEventAddingSpinner,isEditingSpinner等。我将需要创建操作所有这些标志的动作,因为许多标志都是基于redux-thunk结果。即:发送请求时显示微调器,从服务器接收到错误时切换isError……等
我确定有一些优雅的方法可以解决这个问题?
答案 0 :(得分:0)
正如我们在评论中讨论的那样,您可能会看到如下状态:
store = {
event: <state>
attendee: <state>
locations: <state>,
uiFlags: {
showAddEventPopup: false,
showEditEventPopup: false,
isEventAddingSpinner: false,
isEditingSpinner: false
}
}
使用uiFlags
减速器,例如:
const getDefaultState => ({
showAddEventPopup: false,
showEditEventPopup: false,
isEventAddingSpinner: false,
isEditingSpinner: false
});
export const ACTION = {
ENABLE_FLAG: 'enableUiFlag'
DISABLE_FLAG: 'disableUiFlag',
TOGGLE_FLAG: 'toggleUiFlag',
RESET_ALL_FLAGS: 'resetUiFlags'
}
const reducer (state = getDefaultState(), action = {}) => {
const {type, payload} = action;
if (!payload) return state;
switch(type) {
case ACTION.ENABLE_FLAG: {
return {
...state,
[payload]: true
}
}
case ACTION.DISABLE_FLAG: {
return {
...state,
[payload]: false
}
}
case ACTION.TOGGLE_FLAG: {
return {
...state,
[payload]: !state[payload]
}
}
case ACTION.RESET_ALL_FLAGS: {
return getDefaultState();
}
default: {
return state;
}
}
}
像这样的重击:
import {ACTIONS} from './ui-flag-reducer'
function enableUiFlag(flagType) {
return dispatch => {
dispatch({
type: ACTION.ENABLE_FLAG,
payload: 'showEditEventPopup'
})
};
}