解析数据在行动
问题描述:
我我的应用程序连接到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的数据和发送那就是减速器而不是原始数据。
有没有办法做到这一点,而不是在这里做动作的组件?还是应该将转换功能移至减速器?
答
是的,这是可能的。你应该使用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
}
答
你在说什么是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
};
});
}
那不是测试,您将在终极版文档了解如何准确地将其应用到您的需求。
我真的不明白你在问什么。你有'response.data'返回。你可以在那里做任何转换并给结果赋予“有效载荷” – xiaofan2406