我正在将我的应用程序连接到API,操作看起来像这样
export function getDayRoutes(date){
const request = api().get(`/rest/routes/${date}`);
let routes = null;
//code here to transform the data
request.then((response)=>{
routes = response.data;
});
return {
type: GET_DAYROUTES,
payload: routes
}
}
我想要发生的是解析和转换我将从API接收的数据并将其发送到reducer而不是原始数据。
有没有办法解决这个问题,而不是在动作中的组件中进行此操作?或者我应该将转换函数移动到reducer?
答案 0 :(得分:1)
是的,这是可能的。您应该使用thunk middleware for redux。当你收到你的回复时,你可以修改它以满足你的需求,然后将它发送到减速器。贝娄就是一个例子:
export function getDayRoutes(date){
return (dispatch) => {
fetch('/rest/routes/' + date).then((response)=>{
routes = response.data;
dispatch({
type: GET_DAYROUTES,
payload: parseResponse(response);
});
});
}
}
const parseResponse = (response) => {
//return desired modified response
}
答案 1 :(得分:0)
您所谈论的是asynchronous actions。
从您的示例中可能看起来像这样:
export function getDayRoutes(date){
const request = api().get(`/rest/routes/${date}`);
let routes = null;
//code here to transform the data
return request.then((response)=>{
routes = response.data;
return {
type: GET_DAYROUTES,
payload: routes
};
});
}
未经测试,您将在redux文档中看到如何将其完全应用于您的需求。