使用 React、Redux 和 Thunk 的组合,我有以下内容:
动作.js
import $ from 'jquery';
import * as types from '../constants/ActionTypes';
import { API_PATH } from '../constants/Config';
export function coursesLoaded(courses) {
return { type: types.COURSES_LOADED, courses };
}
export function fetchData() {
return (dispatch) => {
return $.getJSON(API_PATH).then((response) => {
dispatch(coursesLoaded(response.result));
});
};
}
减速器.js
import { routerReducer as routing } from 'react-router-redux';
import { combineReducers } from 'redux';
import * as types from '../constants/ActionTypes';
const initialState = {
courses: [],
};
function main(state = initialState, action) {
switch(action.type) {
case types.COURSES_LOADED:
return {
...state,
courses: action.courses,
};
default:
return state;
}
}
const rootReducer = combineReducers({ main, routing });
export default rootReducer;
上面的两个片段坐得很好,我觉得它们符合 Redux 的意图。我现在想在响应中返回的字段到达容器之前对其进行一些修改。
例如,响应可能是:
[
{ code: "R101", name: "Intro to Redux", author: "Dan" },
{ code: "R102", name: "Middleware", author: "Dan" },
]
我想将其更改为(为简单起见的简单示例):
[
{ code: "R101", name: "Intro to Redux", author: "Dan", additionalProperty: "r101_intro_to_redux" },
{ code: "R102", name: "Middleware", author: "Dan", additionalProperty: "r102_middleware" },
]
迄今为止的研究
选项一 查看 Redux 上的异步示例,我可以看到这里的响应很轻松: https ://github.com/reactjs/redux/blob/master/examples/async/actions/index.js#L33
选项二 查看其他 Stackoverflow 问题,它让我相信将其排除在操作之外更有意义,因为 reducer 应该是修改状态的东西(但也许这并不能真正算作状态?): Redux - 在哪里准备数据
选项三 我倾向于认为这是中间件的工作——这就是 normalizr 处理它的方式,但我找不到任何非被动中间件示例。如果中间件是这里的选择,中间件应该调度某种 SET_STATE 动作,还是可以自由地在中间件中更新状态?
编辑
试验了一些中间件,比如:
import { lowerCase, snakeCase } from 'lodash';
import * as types from '../constants/ActionTypes';
export default store => next => action => {
if(action.type == types.COURSES_LOADED) {
action.courses = action.courses.map((course) => {
course.additionalProperty = snakeCase(lowerCase(`${course.code} ${course.name}`));
return course;
});
}
return next(action);
}
它似乎工作正常 - 这确实是中间件的意图吗?原始问题成立 - 理想地点在哪里?