我是React / Redux的新手,我有一个问题,我无法在其他任何地方找到答案。
在你的容器中,你必须从redux
状态获取所需的道具。显然,在mapStateToProps
内解构状态是一个坏主意,容器不应该知道状态。
所以我们有selectors
。 Selectors
很好,它们可以重复使用或组合,容器可以使用selectors
来获取所需的数据,而无需了解状态的结构,但我仍然无法找到一种合理的方式来组织我的选择器。
事情是状态形状可能在将来发生变化,在这种情况下,我们必须更新我们的selectors
,您不希望获得不正确的数据,或者更糟糕的是,获得{{1 }}。
丹·阿布拉莫夫(Dan Abramov)有一个关于egghead的课程(帮助我开始使用runtime errors
,非常棒的课程),他的工作基本上是导出redux
与相关的缩减器(you can watch the video here或{{ 3}}),这是有道理的,因为当你更新selectors
时,你知道你只需要更新相关的reducer
(它们在同一个文件中)。
但正如你在代码中看到的那样,一切都必须通过root reducer,而不仅仅是,如果我需要在selectors
中获取一些数据,我必须创建"leaf reducer"
在selectors
,reducer
以及所有中间root reducer
中,这似乎不是一个好主意。
reducers
?答案 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.