组织选择者的合理方式?

时间:2016-12-09 09:46:19

标签: reactjs redux

我是React / Redux的新手,我有一个问题,我无法在其他任何地方找到答案。

在你的容器中,你必须从redux状态获取所需的道具。显然,在mapStateToProps内解构状态是一个坏主意,容器不应该知道状态。

所以我们有selectorsSelectors很好,它们可以重复使用或组合,容器可以使用selectors来获取所需的数据,而无需了解状态的结构,但我仍然无法找到一种合理的方式来组织我的选择器。

事情是状态形状可能在将来发生变化,在这种情况下,我们必须更新我们的selectors,您不希望获得不正确的数据,或者更糟糕的是,获得{{1 }}。

  • 更新状态树后,您如何知道需要更新哪些选择器?

丹·阿布拉莫夫(Dan Abramov)有一个关于egghead的课程(帮助我开始使用runtime errors,非常棒的课程),他的工作基本上是导出redux与相关的缩减器(you can watch the video here或{{ 3}}),这是有道理的,因为当你更新selectors时,你知道你只需要更新相关的reducer(它们在同一个文件中)。

但正如你在代码中看到的那样,一切都必须通过root reducer,而不仅仅是,如果我需要在selectors中获取一些数据,我必须创建"leaf reducer"selectorsreducer以及所有中间root reducer中,这似乎不是一个好主意。

  • 那么如何整理reducers

1 个答案:

答案 0 :(得分:1)

The state of my app depends on the topic and has a hyrarchical form like

state
- ui
  - topic1
    - setting1
    - setting2
  - topic2
    - setting1
    - setting2
- user
  - name
  - role
- items
  - currentlySelectedItem
  - listOfAllItems

I'm using https://github.com/reactjs/reselect to create effitient and composable selectors. In my file structure you'll find the selectors ordered in a similar way:

folder1
folder2
redux-actions
redux-reducers
redux-selectors
- uiSelectors.js
- userSelectors.js
- itemsSelectors.js
...

The file uiSelectors.js contains the selectors for state.ui. If I feel like, I add a file uiTopic1Selectors.js. Of course, this could become confusing if you have a realy big app but for me it works. Btw: I use a similar structure for my reducers.

When I change the state, I'll have to change some selectors. Because my selectors are composable, I usually don't have to change too much.

The stateToProps function I usually place in the file of the page itself or a page1Selector.js file in the page folder.