通常,我们将执行以下操作以使用 redux-actions 库
定义一个设置的redux action&reducer。
export const {
open,
close,
send
} = createActions({
OPEN: payload => ({
payload
}),
CLOSE: payload => ({
payload
}),
SEND: payload => ({
payload,
})
});
export const combinedReducer = createActions({
[open]: (state, action) => { /*you do someting*/ },
[close]: (state, action) => { /*you do someting*/ },
[send]: (state, action) => { /*you do someting*/ }
});
/*in some where , we are going to handle the a triggered action type respectively in a switch statement.
but we have to use string concatenation to make the switch express strict equal pass , any graceful solution ? */
switch (action.type) {
case open + "":
//do someting
break;
case close + "":
//do someting
break;
case send + "":
//do someting
break;
}
上面生成的
变量打开,关闭,发送实际上是函数类型及其 toString( )被redux-action lib覆盖,以导出“ OPEN” ,“ CLOSE” ,“发送” < / p>
但是,如果我们想在switch语句中重用这些操作类型,则必须以一种笨拙的方式与串联,才能通过switch表达。
在处理强制执行严格相等比较的switch语句解析时,有什么优美的方法可以避免这种愚蠢的代码 ===
提前谢谢。
答案 0 :(得分:1)
我可能误解了您的问题,所以我以前的回答可能无法满足您的要求。
我使用的另一种技术,同时使用createActions()
和switch/case
如下:
import { createAction } from 'redux-actions'
// your action creators
export const myAction = createAction('ACTION_TYPE')
// your store slice/reducers
const defaultSliceState = {}
export const slice = (state = defaultSliceState, action) => {
switch(action.type) {
case myAction().type:
return Object.assign({}, state, { someValue: action.payload })
}
}
如果您需要强制执行严格的相等性,而又不必担心遵循典型/可爱/整洁的模式,则可以使用以下方法:
// your store slice/reducers
const ACTION_TYPE_1 = 'ACTION_TYPE_1'
const ACTION_TYPE_2 = 'ACTION_TYPE_2'
// add your action creators here: const myAction = createAction(ACTION_TYPE)
// ...
const defaultSliceState = {}
export const slice = (state = defaultSliceState, action) => {
switch(true) {
case action.type === ACTION_TYPE_1:
return Object.assign({}, state, { someValue: action.payload })
case action.type === ACTION_TYPE_2:
return Object.assign({}, state, { otherValue: doSomething(action.payload) })
}
}
...但是如果您唯一关心的是严格的平等,则甚至不需要这样做。通过一个小实验,我发现switch/case
已经使用严格的相等性检查。
function match (arg) {
switch(arg) {
case 1: return "matched num"
case '1': return "matched str"
}
}
match(1) // -> matched num
match('1') // -> matched str
答案 1 :(得分:0)
一种使用handleAction
或handleActions
函数的方法,也由redux-actions提供。您不必使用switch
例写长的[action.type]
语句,而是使用这些功能将动作创建者映射到化简器。
这类似于我喜欢的方式:
import { createAction, handleActions } from 'redux-actions'
// your action creators
export const myAction = createAction('ACTION_TYPE`)
// your reducer (this example doesn't do anything useful)
const myReducer = (state, action) => Object.assign({}, state, { someValue: action.payload })
const sliceDefaultValue = {}
export const slice = handleActions({
[myAction]: myReducer
}, sliceDefaultValue)
handleAction
函数文档位于此处:https://redux-actions.js.org/api/handleaction。