我正在学习 React 中的 RxJS/Redux-Observable。
但是我有一个关于return Promise
的问题。
不使用 RxJS/Redux-Observable
这样我就可以将 promise 返回给组件,让它可以使用 .then()
进行下一步操作
在 React 的 Action 中
export const getData = () => (dispatch) => {
try {
const dataResponse = await dataAPI.getData();
dispatch(getDataAction(dataResponse));
return Promise.resolve(dataResponse);
} catch (error) {
return Promise.reject(error);
}
}
在 React 的组件中
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// I can use this response action for some UX Action.
})
}
使用 RxJS/Redux-Observable
我不知道如何返回 promise
在 React 的史诗 Action 中
export const getDataEpic = (action$, state$) => {
return action$.pipe(
ofType(FETCH_DATA),
mergeMap(action => {
let _response = ajax.getJSON(dataAPI.getData());
return _response.pipe(
delay(3000),
map(response => {
return fetchDataFulfilledAction(response);
}),
takeUntil(action$.pipe(
filter(
action => action.type === CANCEL_FETCH_DATA
)
))
)
})
);
}
在 React 的组件中
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// How to get this response result ?
})
}
我知道使用 Reducer 是一种处理方式,但我仍然想知道如何返回 promise 。
谢谢大家
最佳答案
所以当我们返回一个 promise 时你犯了一个典型的错误你不应该为成功或错误返回一个新的 promise 而是返回两个函数:
resolve -> 为了成功将它与 then 链接起来 reject -> 因为 faileure 将它与 catch 链接起来了!
希望这段代码能帮到你,如果你需要澄清,请告诉我
export const getData = () => (dispatch) => new Promise((resolve, reject) => {
const dataResponse = await dataAPI.getData();
dispatch(getDataAction(dataResponse))
if(dataResponse.status === '200') {
return resolve(dataResponse) }
else {
return reject(dataResponse.error)
}
})
关于javascript - 如何在 React 中使用 Rxjs 返回 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684635/