【问题标题】:React / Redux App Issue Fetching Data from MongoDB via APIReact / Redux App 问题通过 API 从 MongoDB 获取数据
【发布时间】:2018-01-26 13:29:59
【问题描述】:

我是 Redux 的新手,我使用 Campaign / Products / Users 以及来自 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 传递状态并应将帖子对象添加到商店。 我可以点击 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)

感谢任何帮助!

【问题讨论】:

  • 告诉我们你在哪里combineReducers
  • 我有一个 reducers.js 文件,它包含以下内容—— import { combineReducers } from 'redux'; // 导入 Reducers 从 './modules/App/AppReducer' 导入应用程序; // 将所有 reducer 合并为一个根 reducer export default combineReducers({ app, });
  • 天啊!!史诗般的失败......看起来它没有添加 PostReducer 来组合这里。这成功了:)

标签: reactjs redux store reducers mern


【解决方案1】:

在 combineReducer 文件中,我忘记在 cmets 中添加 free_soul 提到的 PostReducer。

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

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

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2021-09-27
    • 2018-11-17
    • 1970-01-01
    • 2021-02-28
    • 2017-10-18
    • 2019-12-29
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多