React / Redux App Issue Fetching Data from MongoDB via API



我是 Redux 的新手,并使用活动/产品/用户以及来自 MERN v2.0 样板的帖子设置了一个应用程序。

我已经将我的应用程序设置为具有 fetchPosts 操作。 我的页面有以下内容(下半部分的代码(

// Actions required to provide data for this component to render in sever side.
PostListPage.need = [() => {
return fetchPosts();
}];
// Retrieve data from store as props
function mapStateToProps(state) {
return {
posts: getPosts(state)
};
}
PostListPage.contextTypes = {
router: React.PropTypes.object,
};
export default connect(mapStateToProps)(PostListPage);

获取帖子通过状态,并应将帖子对象添加到商店。 我可以点击 API 路由,并看到后端正在按预期工作并加载 JSON 对象。

但是,我的应用程序在 PostReducer 中给了我一个错误——

// Get all posts
export const getPosts = state => state.posts.data;

错误是当我去路线时——

TypeError: Cannot read property 'data' of undefined
at getPosts (/Users/yasirhossain/Projects/showintel/client/modules/Post/PostReducer.js:31:34)
at mapStateToProps (/Users/yasirhossain/Projects/showintel/client/modules/Post/pages/PostListPage/PostListPage.js:48:12)
at Connect.configureFinalMapState (/Users/yasirhossain/Projects/showintel/node_modules/react-redux/lib/components/connect.js:155:27)

任何帮助不胜感激!

在 combineReducer 文件中,我忘了添加 PostReducer,正如free_soul在评论中提到的那样。

export default combineReducers({
app,
posts,
});

导入后减速器并添加它,成功了!

最新更新