Replacing multiple switch statements using functional programming in ReactJS stores and actions
I don't know if this is just me, but switch statements in ReactJS repositories cause an eyesore, so I thought maybe there is a way to replace these switch statements with a better, modular one.
So, I looked on the internet for quite some time and saw that the approach is the way.
Switch
Dispatcher.register(function (action) {
var text;
switch(action.actionType) {
case Constants.CREATE:
create(action.text)
Store.emitChange();
break;
case Constants.UPDATE:
update(action.id, {text:action.text})
Store.emitChange();
break;
case TodoConstants.DESTROY:
destroy(action.id);
Store.emitChange();
break;
default:
}
});
Plan
getAction = function(action) {
var move = {
"CREATE": function() {create(action.text)},
"UPDATE": function() {update(action.id, {text: action.text})},
"DESTROY": function() {delete(action.id)}
}
return move[action.type](); // if key exist
}
The first problem
I do not want to CREATE
, UPDATE
, DESTROY
as functions of names, because it is not flexible, and I lost the use of constants , so that there is a way that I could still use Constant.CREATE
, Constant.UPDATE
and Constant.DESTROY
as function names?
Second problem
Thus, in theory I can modulate each action CREATE
, UPDATE
, DESTROY
in separate files, and I use the browser.
So how can I do this?
source to share
No one has answered this question yet
Check out similar questions: