我对redux-saga还是很陌生,并且正在尝试进行一个简单的演示工作,该工作进行API调用并执行分页。据我了解,redux-saga流程应按以下方式工作。 Page-Size用于限制api调用时要显示的数据数量。
const PAGE_SIZE = 1;
export const fetchItems = page => (dispatch, getState) => {
const state = getState();
const offset = page * PAGE_SIZE;
dispatch(setItemsCurrentPage(page));
if (getIsPageFetched(state, page)) {
return;
}
dispatch(fetchItemsRequest());
fromItems.fetchItems({
limit: PAGE_SIZE,
offset,
})
.then((response) => {
const pageCount = Math.ceil(response.count / PAGE_SIZE);
dispatch(fetchItemsResponse({
items: response.results,
page,
pageCount,
}));
})
};
答案 0 :(得分:0)
selector.js
/** * Direct selector to the container state domain */ const selectState = () => state => state.get("selectState"); export { selectState };
saga.js
import { call, put, select } from "redux-saga/effects";
import {selectState} from "./selector";
export function* fetchItems(page) {
try {
const state= yeild select(selectState())
const offset=page * PAGE_SIZE;
yield put(setItemsCurrentPage(page));
/**for api calls you need use **call** method**/
const data={limit:PAGE_SIZE,offset};
const requestUrl = `${url}`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
const response = yield call(request, requestUrl, options);
const pageCount = Math.ceil(response.count / PAGE_SIZE);
yield put(fetchItemResponse({items:response.results,page,pageCount}))
} catch (e) {
yield put(LoadingError(e));
}
}
* note选择器基本上用于从状态中获取数据,在thunk中,我们使用getState()并导航到数据,但在传奇中,您需要选择器来访问特定状态数据。 Put 用于设置要存储的数据(基本上是一个动作),调用用于api命中。请通过一些帖子,youtube视频或官方文档进行清晰说明,但在我看来,笨拙更容易理解。
答案 1 :(得分:0)
redux传奇中的等效代码如下所示:
export function* watchFetch() {
yield takeEvery('FETCH_ITEMS', fetchItems);
}
export function* fetchItems(action) {
const offset = action.page * PAGE_SIZE;
yield put(setItemsCurrentPage(page));
if (yield select(getIsPageFetched, page)) {
return;
}
yield put(fetchItemsRequest());
const response = yield fromItems.fetchItems({
limit: PAGE_SIZE,
offset,
});
const pageCount = Math.ceil(response.count / PAGE_SIZE);
yield put(fetchItemsResponse({
items: response.results,
page,
pageCount,
}));
}