我正在学习redux-saga,到目前为止,我已经创建了具有正常本地应用程序状态(加号和减号按钮)的基本项目,但是异步部分存在问题。
在请求操作期间基本上redux卡住了。
链接执行代码和框: https://codesandbox.io/s/recursing-dirac-vxy1s
这是代码的一部分,无法按照@Clarity建议使用:
actions.js
export const CLICKER_GET_POST_REQUEST = "CLICKER_GET_POST_REQUEST";
export const CLICKER_GET_POST_SUCCESS = "CLICKER_GET_POST_SUCCESS";
export const CLICKER_GET_POST_FAILED = "CLICKER_GET_POST_FAILED";
export const clickerGetPostRequest = () => ({
type: CLICKER_GET_POST_REQUEST
});
export const clickerGetPostSuccess = payload => ({
type: CLICKER_GET_POST_SUCCESS,
payload
});
export const clickerGetPostFailed = payload => ({
type: CLICKER_GET_POST_FAILED,
payload
});
reducer.js
const initialState = {
post: {},
isLoading: false,
isError: false
};
export default function ClickerReducer(state = initialState, action) {
switch (action.type) {
case CLICKER_GET_POST_REQUEST:
return {
...state,
isLoading: true
};
case CLICKER_GET_POST_SUCCESS:
return {
...state,
isLoading: false,
post: action.payload
};
case CLICKER_GET_POST_FAILED:
return {
...state,
isLoading: false,
isError: true
};
default:
return state;
}
}
saga.js
export default function*() {
yield [
takeEvery(CLICKER_GET_POST_REQUEST, fetchPost)
];
}
function* fetchPost() {
try {
const response = yield call(
fetch,
"https://jsonplaceholder.typicode.com/posts/1"
);
const data = yield response.json();
yield put(clickerGetPostSuccess(data));
} catch (err) {
yield put(clickerGetPostFailed());
}
}
最后执行了“ clickerGetPostRequest”,但 “ clickerGetPostSuccess”或“ clickerGetPostFailed”都不会运行。
答案 0 :(得分:0)
产生数组时,需要将数组包装在all
中:
import { all } from "redux-saga/effects";
export default function*() {
yield all([
takeEvery(CLICKER_GET_POST_REQUEST, fetchPost)
]);
}
rootSaga.js
中的sagas阵列也是如此。