【发布时间】:2020-03-27 07:45:00
【问题描述】:
我有一个对象数组作为初始状态。该数组保存用户问题/响应数据。在 HTML 页面上有一个 material-ui 切换开关来控制问题应该是公开的还是私有的。我知道 redux 建议在 action 中保留逻辑而不是 reducer,但这是我想出的解决方案。 “toggleSwitch reducer”是一个可接受的解决方案还是我创建了一个反模式?
请注意,我使用“reducer helper”而不是“switch 语句”来减少样板代码。 先感谢您。我对 redux 很陌生。
// ACTION
export const toggleQuestion = (questionId) => {
return {
type: TOGGLE_QUESTION,
payload: {
questionId
}
}
}
//REDUCER
const initialState = [{
id: '1',
firstName: 'James',
lastName: 'Smith',
question: 'Ask a question here?',
response: 'This is an answer to the question',
public: true,
created: '2019-23-11T01:50:00+00:00',
modified: null
},
{
id: '2',
firstName: 'Taylor',
lastName: 'Johnson',
question: 'Ask another question here?',
response: 'Here is another answer to another question',
public: true,
created: '2019-23-11T01:50:00+00:00',
modified: null
}
];
const toggleSwitch = (state, payload) => {
return [
...state.map((item) => {
if (item.id === payload.questionId) {
return Object.assign(item, {
public: !item.public
})
}
return item
})
]
}
export default createReducer(initialState, {
[CREATE_QUESTION]: createQuestion,
[UPDATE_QUESTION]: updateQuestion,
[DELETE_QUESTION]: deleteQuestion,
[TOGGLE_QUESTION]: toggleQuestion
});
// HELPER TO CREATE THE REDUCER
export const createReducer = (initialState, fnMap) => {
return (state = initialState, {
type,
payload
}) => {
const handler = fnMap[type];
return handler ? handler(state, payload) : state
}
}
【问题讨论】:
-
旁注:您正在使用
Object.assign改变状态。应该是Object.assign({}, item, { public: !item.public })。另外,我认为使用[ ...state.map(---) ]是多余的。您可以删除括号并使用state.map(---)。
标签: reactjs redux react-redux reducers