【问题标题】:Should every React component have it's own slice, when using createEntityAdapter?使用 createEntityAdapter 时,每个 React 组件都应该有自己的切片吗?
【发布时间】:2021-05-25 21:12:06
【问题描述】:

我正在使用 Redux-tookit 的 createSlicecreateEntityAdapter 处理标准化数据。

这是一个典型的博客应用,包含(帖子、cmets、用户)-实体

通常,在使用createEntityAdapter 之前,我会:

  1. postsSlice中获取、规范化和存储数据
    所以我的 postSlice state 看起来像这样:
    blogPosts: {entities: {posts: {}, users:{}, comments: {}}, ids:[]}
  2. idpostsSlice的状态获取到Posts组件
  3. 将评论/用户 idPosts 传递给子组件 - Comment User 组件,他们将使用传递的 id 获取数据,其中选择器连接到父级的 postSlice 状态
const postsAdapter = createEntityAdapter();

const postsSlice = createSlice({
  name: "posts",
  initialState: postsAdapter.getInitialState(),

  reducers: {
    setPosts: (state, { payload }) =>
      postsAdapter.setAll(state, payload.entities.posts),
  },
});

问题是:

  • 使用createEntityAdapter
    由于我们使用的是createEntityAdapter.getInitialState(),因此我们在每个切片中都会得到相同的initialState {entities: {} ids: []} 模式。
  • 这不允许像我以前那样拥有 initialState:
    blogPosts: {entities: {posts: {}, users:{}, comments: {}}, ids:[]}

是否应该每个组件(PostsUserComment)都有自己的切片/reducer,并使用来自同一端点的 thunk 获取自己的数据?

这样: (根据 createEntityAdapter.getInitialState() 模式)

  • postSlice state 将只包含 post Entity - entities: {posts: {}, ids:[]}
  • commentSlice 状态 - cmets 实体 - entities: {comments: {}, ids:[]}
  • 等等……

【问题讨论】:

  • 我个人的偏好是有一个 entities 切片,其中包含每个实体类型的属性。

标签: reactjs redux react-redux redux-toolkit normalizr


【解决方案1】:

没有。 组件和 Redux 状态结构之间从未存在 1:1 的关联。相反,您应该organize your state in terms of your data types and update logic,并且组件应该根据自己的需要访问和重新调整这些数据。

请注意, multiple ways to approach structuring that data in the store even if it's being normalized。例如,您可以将每种数据类型都作为其自己的顶级切片,或者拥有一个共享的 entities reducer,其中每种类型都嵌套在其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    相关资源
    最近更新 更多