React / Redux 应用程序问题通过 API 从 MongoDB 获取数据

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);

Get Posts 传递状态并且应该将 posts 对象添加到商店。 我可以点击 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 文件中,我忘记添加评论中 free_soul 提到的 PostReducer。

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

导入 PostReducer 并添加它,成功了!