【发布时间】:2021-02-06 16:10:40
【问题描述】:
恢复初始状态的最佳方法是什么? 对于此示例,假设我可以通过调度以下操作来编辑汽车:
dispatch(actions.editModel('Civic'));
dispatch(actions.editType({
make: 'Ford',
model: 'Focus'
}));
dispatch(actions.restoreInitialState());
我的减速器是这样的:
const initialState = {
id: '1',
vehicle: 'car',
type: {
make: 'Honda',
model: 'Accord'
},
license: 'abc'
}
export default createReducer({
[actions.editType]: (state, payload) => ({
...state,
type: payload // payload is an object
}),
[actions.editModel]: (state, payload) => ({
...state,
type: {
...state.type,
model: payload // payload is a string
}
}),
[actions.restoreInitialState]: (state) => ({
state: initialState // initial state has nested objects
})
}, initialState)
是否存在我正在改变我的状态或错误地恢复我的初始状态的风险? 这可能有点矫枉过正,但我正在考虑像这样编辑我的减速器:
export default createReducer({
[actions.editType]: (state, payload) => ({
...state,
type: {
...payload // payload is an object
}
}),
[actions.editModel]: (state, payload) => ({
...state,
type: {
...state.type,
model: payload // payload is a string
}
}),
[actions.restoreInitialState]: (state) => ({
state: {
...initialState // initial state has nested objects
}
})
}, initialState)
当我通过有效负载传递对象与仅引用我的初始状态时有区别吗? (加上我的初始状态包含嵌套对象)
【问题讨论】:
标签: javascript reactjs redux reducers