[英]Return a promise for a simple action creator in react using react-redux
[英]How to return a promise for a simple redux action creator?
我有一個函數add
,其中沒有承諾返回給調用者。
例如:
let add = (foo) => {this.props.save(foo)};
在我的應用程序的另一個功能,我想做:
...
return add()
.then( ... do something else here ... );
我只想等到add()
完成后再做其他事情。 我知道async save
不會返回一個promise。 它是一個簡單的redux動作。
export const save = (something) => (dispatch) => {
ApiUtil.patch(`google.com`, { data: {
something } }).
then(() => {
dispatch({ type: Constants.SET_FALSE });
},
() => {
dispatch({ type: Constants.SET_SAVE_FAILED,
payload: { saveFailed: true } });
});
};
我把它貼在這里展示行動
在我看來,您正在使用redux-thunk進行異步操作,因為您的add
操作創建者實際上正在返回一個接受dispatch
而不是簡單操作對象的函數。
如果你正在使用redux-thunk,那么你從thunk返回的任何內容都將被傳播回來。 因此,如果您修改代碼,則:
let add = (foo) => this.props.save(foo); // Now returns result of save
然后將您的thunk更新為:
export const add = (something) => (dispatch) =>
ApiUtil.patch(`google.com`, { data: { something } })
.then(() => { dispatch({ type: Constants.SET_FALSE }); },
() => { dispatch({ type: Constants.SET_SAVE_FAILED, payload: { saveFailed: true }});}
);
(你會注意到我刪除了最外面的curlies),然后來自ApiUtil的承諾應該一直冒泡,你應該能夠。然后你就可以了。
首先,您必須了解this.props.save()
返回的內容。 如果它返回一個promise,那么你只需要從add中返回:
const add = (foo) => { return this.props.save(foo); }
所以問題就在於save的定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.