对于异步请求,我使用的是 redux-saga
。
在我的组件中,我调用一个操作来恢复用户密码,它正在工作,但我需要一种方法来知道,在我的组件中,我分派(dispatch)的操作已成功执行,如下所示:
成功返回如下:
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 无信息
最佳答案
您应该将此视为应用程序中的状态更改。
添加一个接收这些操作RECOVER_USER_PASSWORD_SUCCESS
或RECOVER_USER_PASSWORD_FAILURE
的reducer,然后使用有关请求状态的信息更新存储。例如:
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)
关于javascript - ReactJS - 获取调度结果的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775137/