我有两个应用程序在我的CRA中,使用相同的UI,但做的事情略有不同。目前,我正在为这两个应用程序使用很多类似的缩减程序,我想知道让它们可重用而不是重复代码的最好方法?
app1:
export default (state: App1State = initialState, action: ReducerAction) => {
switch (action.type) {
case APP_1.ACTION:
return {
...state,
id: 123,
app1SpecificState: 'app1'
}
default:
return state
}
}app2:
export default (state: App2State = initialState, action: ReducerAction) => {
switch (action.type) {
case APP_2.ACTION:
return {
...state,
id: 123,
app2SpecificState: 'app1'
}
default:
return state
}
}因此,为了将它们结合起来,我正在考虑这样做:
export default (state: App1State = initialState, action: ReducerAction) => {
if (process.env.APP_NAME === 'app2') {
(state as App2State) = App2State
}
switch (action.type) {
case APP_1.ACTION:
return {
...state,
id: 123,
app1SpecificState: 'app1'
}
case APP_2.ACTION:
return {
...state,
id: 123,
app2SpecificState: 'app2'
}
default:
return state
}
}我想知道a)这是否有意义b)这是一个好主意c)有更好的方法来实现这一点吗?
我也不想在我所有的“共享”缩减程序中重复if语句,所以如果可能的话,最好对其进行抽象。可能是临时的,如果这在这里是可能的话?
发布于 2019-10-10 17:29:32
redux文档提供了解决这个问题的方法,请查看:
如果您需要动态创建redux store的新部分,也可以稍后添加更多的reducers:
发布于 2019-10-10 18:51:49
为了动态更新你的存储,你应该像下面这样用属性名来分派你的数据:
dispatch({
type: APP.ACTION,
payload: "app1",
specificState: "app1SpecificState"
})
dispatch({
type: APP.ACTION,
payload: "app2",
specificState: "app2SpecificState"
})然后在你的reducer中,你可以像这样使用:
case APP.ACTION:
return {
...state,
id: 123,
[action.specificState]: action.payload
}这与动态更新状态的原理相同。
https://stackoverflow.com/questions/58319545
复制相似问题