从商店中选择复杂数据

时间:2018-03-08 23:20:06

标签: reactjs redux react-redux reselect

我的商店:

{
  entities: {
    posts: {
      6: {
        id: 1,
        title: 'Some title',
        account_id: 2,
        ...
      }
    }
    comments: {
      1: {
        id: 1,
        name: 'Some name',
        ...
      }
    }
    accounts: {
      1: {
        id: 2,
        name: 'Antonio',
        ...
      }
    }
  }
  pagination: {
    // Comments by POST ID
    comments: {
      6: {
        ids: [1,2, ..., 6],
        isFetching: false,
        ...
      }
    }
  }
}

对于每个帖子页面,我都有一个评论部分,其中我显示所有评论。评论组件包括作者username和评论详细信息。评论和作者作为实体(commentsaccounts)单独存储在商店中,并且仅通过 FK account_id)连接。我需要的是显示帖子的所有评论,包括作者信息(username)。

所以,我决定为此创建2个(reselect)选择器:

const getComments = state => state.entities.comments;
const getCommentIds = (state, props) => {
  const id = props.match.params.post;
  const comments = state.pagination.comments[id];

  return (comments && !comments.isFetching) ? comments.ids : [];
}
const getUsers = state => state.entities.accounts;

export const getPostComments = createSelector(
  [ getComments, getCommentIds ], (comments, ids) => {
    return ids.map(id => comments[id]);
  }
)

export const getCommentsWithAuthors = createSelector(
  [ getPostComments, getUsers ], (comments, users) => {
    return comments.map(comment => {
      const { username } = users[comment.account_id];

      return Object.assign({}, comment, { username });
    });
  }
)

mapStateToProps 功能:

const mapStateToProps = (state, props) => {
  const id = props.match.params.post;
  const { posts } = state.entities;

  return {
    post: state.entities.posts[id],
    comments: getCommentsWithAuthors(state, props)
  }
}

一切正常,但我想知道这是否是常见方法,或者我的state对象的架构可能很差,这就是我遇到这样一个解决方案的原因?

0 个答案:

没有答案