使用反應,終極版和咚的組合,我有以下:在哪裏可以修改響應數據?
actions.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;
兩個片段以上仰臥
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));
});
};
}
reducer.js好吧,我覺得他們符合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上的異步示例,我可以看到ERE是光觸摸這裏的響應: https://github.com/reactjs/redux/blob/master/examples/async/actions/index.js#L33
方案二 綜觀其他#1的問題,這使我相信保持它的行動更有意義,因爲還原劑應該是什麼修改狀態(但也許這並不能真正算作狀態): Redux - where to prepare data
方案三 我有一個傾斜,這是中間件的工作 - 是這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);
}
這似乎很好地工作 - 這是確實的中間件的用意何在?原始問題成立 - 理想的地方在哪裏?
我建議將API提取邏輯提取到一個'DataService'中,它也能夠修改返回的JSON對象。結果你的'.getJSON(API_PATH)'成爲'DataService.getMyData(path)','then()'已經具有正確格式化的數據。 – lux