对于异步请求,我正在使用redux-saga
。
在我的组件中,我调用了一个操作来恢复用户密码,它可以正常工作,但是我需要一种方法来在我的组件中知道我分派的操作已成功执行,就像这样:
下面的成功正在返回:
payload: {email: "test@mail.com"}
type: "@user/RecoverUserPasswordRequest"
__proto__: Object
我的组件:
async function onSubmit(data) {
const success = await dispatch(recoverUserPasswordRequestAction(data.email))
if (success) {
// do something
}
}
我的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,
}
}
我的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没有信息
答案 0 :(得分:1)
您应将此视为应用程序中的状态更改。
添加一个减速器,以接收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)