在sagas中获取地图内的数据



我在sagas中的map函数中获取数据时遇到了问题。

我想通过sagas在Load上初始化我的帖子。

我正在调度一个具有生成器功能的动作,如下所示:

export function* initPosts() {
try {
//get categories
const categories = yield call(fetchAll);
//fetch 6 posts per category
const posts = yield all(
categories.map((category, index) => {
const { _id, name, slug } = category;
//insert posts in array of category
const postArr = call(fetchByCategory, { id: _id, skip: 0, limit: 6 });
return { name, _id, slug, index, posts: postArr };
})
);
//dispatch payload to success
yield put(fetchInitPostSuccess(posts));
} catch (error) {
yield put(fetchInitPostFailure(error.message));
}
}
export function* watcherFetchInitPosts() {
yield takeLatest(PostActionTypes.POST_FETCH_INIT_START, initPosts);
}

成功后,我将有效载荷置于状态。

当我检查记录器时,除了postsAr之外,一切看起来都很好。

在记录器中,有效载荷显示posts数组包含以下内容:

index: 1
name: "Category 3"
slug: "category-3"
_id: "5f2952d394e59b3c34605f64"
posts:
@@redux-saga/IO: true
combinator: false
payload: {context: null, args: Array(1), fn: ƒ}
type: "CALL"
__proto__: Object

但是,当我调度一个只调用fetchByCategory的操作时,它的有效负载是正确的。像这里:

export function* fetchPostsByCategory({ payload }) {
try {
const posts = yield call(fetchByCategory, payload);
yield put(fetchPostByCategorySuccess(posts));
} catch (error) {
yield put(fetchPostByCategoryFailure(error.message));
}
}
export function* watcherFetchPostsByCategory() {
yield takeLatest(
PostActionTypes.POST_FETCH_BY_CATEGORY_START,
fetchPostsByCategory
);
}

我该怎么办。

更新****我将代码更改为以下内容,只是想看看对fetchByCategory的调用是否有效:

export function* initPosts() {
try {
//get categories
const categories = yield call(fetchAll);
//fetch 6 posts per category
const posts = yield all(
categories.map((category, index) => {
const { _id, name, slug } = category;
return call(fetchByCategory, { id: _id, skip: 0, limit: 6 });      
})
);
//dispatch payload to success
yield put(fetchInitPostSuccess(posts));
} catch (error) {
yield put(fetchInitPostFailure(error.message));
}
}

它可以工作,但我也想用postArray 存储类别名称、id、slug

这是有效的,但我担心它的性能

export function* initPosts() {
try {
//get categories
const categories = yield call(fetchAll);
const fetchedPosts = yield all(
categories.map((category, index) => {
const { _id, name, slug } = category;
return call(fetchByCategory, { id: _id, skip: 0, limit: 6 });
})
);
const mergedCatAndPost = categories.map((category, cIndex) => {
const getPost = fetchedPosts[cIndex];
const { _id, name, slug } = category;
return { name, _id, slug, posts: getPost };
});
//dispatch payload to success
yield put(fetchInitPostSuccess(mergedCatAndPost));
} catch (error) {
yield put(fetchInitPostFailure(error.message));
}
}

最新更新