我在尝试调度fetch之前更改了动作创建者的签名以调用getState
,但现在没有调用fetch。
StartingPoint:我有一个异步操作,使用fetch进行api调用,然后在完成后调度成功或错误操作,如下所示。我从这样的容器中调用此操作,它工作正常:
dispatch(actions.getData());
//来自容器
export function getData(){
return (dispatch : any) => {
return fetch(
'http://localhost:8000/api',{}
).then(
response => response.json()
).then(
json => dispatch(successAction(json)),
err => dispatch(notify("SERVER_ERROR"))
);
}
}
问题是我需要在操作中调用getState
,以便我可以选择要查询的端口。因此,我将getData操作更改为您在下面看到的内容。但是,当我将动作创建者称为此dispatch(actions.getData());
时,虽然console.log
语句正在运行,但它并未进行网络调用。
问题:如何编写getData
函数以允许在运行fetch之前调用getState
? (以及相关的,在发货退货中包装它的目的是什么)?
export const getData = () => (dispatch: any, getState: any) => {
let state = getState();
let url = //code omitted - getting port from state object
console.log("this log statement runs");
return (dispatch : any) => {
return fetch(
url,{}
).then(
response => response.json()
).then(
json => dispatch(successAction(json)),
err => dispatch(notify("SERVER_ERROR"))
);
}
}
添加了Promise支持
const addPromiseSupportToDispatch = (store: any) => {
const rawDispatch = store.dispatch;
return (action: any) => {
if (typeof action.then === 'function') {
return action.then(rawDispatch);
}
return rawDispatch(action);
};
};
store.dispatch = addPromiseSupportToDispatch(store);
答案 0 :(得分:1)
我认为您添加了额外的return
。这应该是正确的代码块
export const getData = () => (dispatch: any, getState: any) => {
let state = getState();
let url = //code omitted - getting port from state object
console.log("this log statement runs");
return fetch(
url,{}
).then(
response => response.json()
).then(
json => dispatch(successAction(json)),
err => dispatch(notify("SERVER_ERROR"))
);
}
修改
如果我必须使用原始代码:
export function getData(){
return (dispatch : any, getState: any) => { // <= second parameter provided by redux-thunk
let url = getState().url; //can call getState here
return fetch(
'http://localhost:8000/api',{}
).then(
response => response.json()
).then(
json => dispatch(successAction(json)),
err => dispatch(notify("SERVER_ERROR"))
);
}
}