gpt4 book ai didi

javascript - 使用 Redux Reselect 过滤评论

转载 作者:行者123 更新时间:2023-11-30 20:27:42 24 4
gpt4 key购买 nike

我正在尝试过滤和显示“postID”与当前帖子 ID 匹配的评论。我正在使用 Redux/Reselect,它可以工作,但有时会返回一个错误,提示 post._id is undefined/null..

代码如下:

const getAllComments = state => state.comments.comments;
const getPost = state => state.posts.post;

export const getCommentsByPostID = createSelector([ getAllComments, getPost ], (comments, post) => {
return comments.filter((c) => c.postID == post._id);
})

我在 getPost(params.id) 之后调用 componentDidMount 中的 getComments() 操作。如何确定帖子已定义?我应该调用 in render 方法吗?

最佳答案

因此,在调用选择器之前,您必须确保您的数据(postscomments)已经获取并可供您使用。

您可以尝试以下流程,稍后(如果适合您),您可以改进它:

  1. 对于每个实体(PostComment 等),您将保留一个名为fetching 的新元属性。使用此属性,您将始终了解数据的当前状态。它还会阻止您对同一资源进行多次 API 调用(假设您有两个组件,它们需要并获取帖子,因此只应调用 1 个 API 请求)。它将具有三个可能的值:

    1. not-started - 数据未启动,未触发数据获取请求。
    2. fetching - 正在获取数据。
    3. fetched- 数据已经获取。
  2. componentDidMount 中,您将调用您的 API 调用(操作创建者),这将分别更改 fetching 状态。

  3. 最后一步是在 mapStateToProps 中,您将在其中调用您的选择器,只有在获取数据时才会这样:
const isFetching = entity => ['not-started', 'fetching'].includes(entity.fetching)

const mapStateToProps = state => {
// Here you wait your data to be fetched,
// and return `isFetching` flag, in order to show a <Loader /> component,
// or something else
if (isFetching(state.posts) || isFetching(state.comments)) return { isFetching: true }

// Here the data is already fetched, and you can call your selectors.
return {
comments: state.comments,
posts: state.posts
}
}

这就是我在项目中使用的流程。正如我已经说过的,您可以开始以非常基本的方式实现它,稍后(如果适合您)您可以创建一些抽象,这些将减少样板代码。例如 - 您可以创建一个 HOC,您将仅在其中传递所需的实体,一旦获取实体,HOC 将呈现您的组件。类似这样的东西:DataProviderHOC(PostsList, ['Post', 'Comment'])PostsList 组件将被呈现,只有当 Post, Comment 实体被获取时。尽可能简单和干净。

关于javascript - 使用 Redux Reselect 过滤评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50705321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com