我正在向我的还原发送很多:
export const setStudent = (data, value, year, group, showStudent) => ({
type: "SET_STUDENT",
data,
value,
year,
group,
showStudent
});
在我的还原器中,我将其发送我需要排序的数据,以及相关参数:
case "SET_STUDENT":
let studentName = data
.find(option => {
return option.id == year;
})
.options.find(option => {
return option.id == group;
})
.options.find(option => {
return option.id == value;
}).label;
return { ...state, student: value, label: studentName };
而不是在操作中发送data
,我可以在我的reducer
中导入它:
import { data } from "../config/calendars.js";
我的mapDispatchToProps
也变得非常混乱:
const mapDispatchToProps = dispatch => ({
fetchEvents: id => dispatch(fetchEvents(id)),
isLoadingCredentials: loadingCredentials =>
dispatch(isLoadingCredentials(loadingCredentials)),
setCredentials: credentials => dispatch(setCredentials(credentials)),
setYear: year => dispatch(setYear(year)),
setGroup: (group, data, year) =>
dispatch(setGroup(group, data, year)),
setStudent: (data, e, year, group, showStudent) =>
dispatch(setStudent(data, e, year, group, showStudent)),
resetForm: () => dispatch(resetForm()),
setAuthenticated: value => dispatch(setAuthenticated(value))
});
您可以使用 mapDispatch
的"对象速记"形式大幅简化代码。只需使用这些动作创建者定义一个对象,例如:
const mapDispatchToProps = {
fetchEvents,
isLoadingCredentials,
setCredentials,
setYear,
setGroup,
setStudent,
resetForm,
setAuthenticated,
}
另外,我猜您可能可以将其中一些"设置"操作合并为单个"USER_FORM_UPDATED"
动作或类似的操作。
如果数据是静态对象,则可以从还原器导入它。它将保持纯粹的功能。但是我会让我的还原器尽可能简单,也许我将此逻辑移至动作创建者。这就是为什么我们首先也可以包含逻辑创建动作创作者的原因。
例如:
import { data } from "../config/calendars.js";
export const setStudent = (value, year, group, showStudent) => {
let studentName = data
.find(option => {
return option.id == year;
})
.options.find(option => {
return option.id == group;
})
.options.find(option => {
return option.id == value;
}).label;
return {
type: "SET_STUDENT",
student: value,
label: studentName
};
}