[英]If a state in my Redux Store is an observable, should I subscribe to it in each component that needs it or subscribe in one place and pass as inputs?
Currently, When a user logs in I subscribe to the user state in my Redux Store in each component that needs the user state.目前,当用户登录时,我在我的 Redux 中订阅用户 state 存储在每个需要用户 state 的组件中。
I want to access the user state in multiple places such as:我想在多个地方访问用户 state,例如:
If my user state is an observable should I be subscribing to it in each component and service that needs to know the userID or only subscribing in one place?如果我的用户 state 是可观察的,我应该在需要知道用户 ID 的每个组件和服务中订阅它还是只在一个地方订阅?
Answer has few points:答案有几点:
You don't need to subscribe to the whole state.您无需订阅整个 state。 You need to subscribe to a specific "slice" of the store using selector
createSelector
.您需要使用选择器
createSelector
订阅商店的特定“切片”。 You can subscribe to it everywhere.您可以在任何地方订阅它。
BUT... few words about good architecture.但是......关于良好建筑的几句话。 It is a good practice to split components into two categories: "smart" and "dumb".
将组件分为两类:“智能”和“哑”是一种很好的做法。
"Smart" - are containers responsible for data resolving and passing it down to children via inputs. “智能” - 是负责数据解析并通过输入将其传递给子级的容器。 Subscribe to state changes here.
在此处订阅 state 更改。
"Dumb" components - are more granular pieces of your app. “哑”组件 - 是您的应用程序中更细化的部分。 They should get data via inputs and emit events via outputs.
他们应该通过输入获取数据并通过输出发出事件。 And contain only some specific logic inside.
并且里面只包含一些特定的逻辑。
This way it will be much easier to have a good structure of the application and to split responsibilities between different parts.这样,拥有良好的应用程序结构并在不同部分之间划分职责会容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.