对于异步请求,我正在使用redux-saga
。
在我的组件中,我调用一个操作来恢复用户密码,它的工作正常,但是我需要一种方法,在我的组件中,我分派的操作已成功执行,如下所示:
<返回:
payload: {email: "[email protected]"}
type: "@user/RecoverUserPasswordRequest"
__proto__: Object
我的组件:
async function onSubmit(data) {
const success = await dispatch(recoverUserPasswordRequestAction(data.email))
if (success) {
// do something
}
}
My actions.js
export function recoverUserPasswordRequest(email) {
return {
type: actions.RECOVER_USER_PASSWORD_REQUEST,
payload: { email },
}
}
export function recoverUserPasswordSuccess(email) {
return {
type: actions.RECOVER_USER_PASSWORD_SUCCESS,
payload: { email },
}
}
export function recoverUserPasswordFailure() {
return {
type: actions.RECOVER_USER_PASSWORD_FAILURE,
}
}
My sagas.js
export function* recoverUserPassword({ payload }) {
const { email } = payload
try {
const response = yield call(api.patch, 'user/forgot-password', {
email
})
// response here if success is only a code 204
console.log('response', response)
yield put(recoverUserPasswordSuccess(email))
} catch (err) {
toast.error('User doesnt exists');
yield put(recoverUserPasswordFailure())
}
}
export default all([
takeLatest(RECOVER_USER_PASSWORD_REQUEST, recoverUserPassword),
])
在我的[[reducer.js中,我没有任何与恢复用户密码有关的内容,就像
RECOVER_USER_PASSWORD_SUCCESS
,因为就像我说的那样,我的传奇的api响应只是代码204,没有任何信息RECOVER_USER_PASSWORD_SUCCESS
或RECOVER_USER_PASSWORD_FAILURE
的减速器,然后使用有关请求状态的信息更新商店。例如:const initialState = {
email: null,
status: null,
}
const recoverPasswordReducer = (state=initialState, action) => {
//...
if (action.type === actions.RECOVER_USER_PASSWORD_SUCCESS) {
return {...initialState, status: True }
}
if (action.type === actions.RECOVER_USER_PASSWORD_SUCCESS) {
return {...initialState, status: False }
}
return state;
}
以后将需要了解操作状态的组件连接到商店时,可以将状态作为mapStateToProps中选择的字段之一。
function mapStateToProps(state) {
return {
/* ... other fields needed from state */
status: state.status
}
}
export connect(mapStateToProps)(ComponentNeedsToKnow)