redux-saga 不起作用,它不会捕获请求操作



我想用redux-saga、redux-toolkit创建一个应用程序。但是当我发送动作时,saga并没有捕捉到那个动作,使它只在请求时停止。下列代码:

  • package-lock
"@reduxjs/toolkit": "^1.9.1",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.13",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"antd": "^5.1.0",
"autoprefixer": "^10.4.13",
"axios": "^1.2.1",
"history": "^5.3.0",
"postcss": "^8.4.19",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-router-dom": "^6.6.1",
"react-scripts": "5.0.1",
"redux-saga": "^1.2.2",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0"
  • store.ts
const sagaMiddleware = createSagaMiddleware();
export const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware({serializableCheck: false}).concat(sagaMiddleware)
})
sagaMiddleware.run(rootSaga);
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
  • rootSaga:
const rootSaga = function* rootSaga() {
yield all([
authSaga(),
]);
}
export default rootSaga;
  • saga.ts
function* loginSaga(action: ReturnType<typeof loginRequest>) {
try {
console.log(action);
const response = yield call(loginApi, action.payload);;
yield put(loginSuccess("response"));
} catch (error) {
yield put(loginFailure(error));
}
}
export default function authSaga() {
return [
takeEvery(loginRequest, loginSaga)
]
}
  • action.ts
export const loginRequest = createAction<LoginPayload>('LOGIN_REQUEST');
export const loginSuccess = createAction('LOGIN_SUCCESS');
export const loginFailure = createAction('LOGIN_FAILURE');

我花了很多时间想弄清楚并修复它,但它不工作

我试了很多次,检查了&和;。但这行不通。Saga中间件不能捕获动作。

  1. 你应该改变你的rootSaga代码来自rootSaga。进入export default function* rootSaga
  2. 在你的传奇中。ts,尝试将export default function authSaga()改为export function* authSaga()

我发现redux-saga非常令人困惑,很难使用。由于您已经在使用redux-toolkit,因此您可以使用createAsyncThunk使这更容易。

const login = createAsyncThunk(
'login',
(payload: LoginPayload) => loginApi(payload)
)

要从组件启动登录过程,使用LoginPayload调度根login操作:

dispatch(login({ username: 'abc', password: 'xyz' }));

中间件将自动捕获这个动作,调用你的API,并为三个阶段调度动作。

你不再需要你的三个createAction调用了,因为login对象(一个"大动作创建器")也包含了三个单独的动作创建器,你可以在你的reducer中使用它们:

  • login.pending
  • login.fulfilled
  • login.rejected

你必须改变你的saga.ts从:

export default function authSaga() {
return [
takeEvery(loginRequest, loginSaga)
]
}

为:

export default function* authSaga() {
yield takeEvery("LOGIN_REQUEST", loginSaga);
}

saga检查已调度的类型,并在看到必须调用的类型时点击。

相关内容

  • 没有找到相关文章

最新更新