[英]Tight coupling among react components
I've been working with react for a little while, and I found out react components heavily depend on one another which is not a good practice in my opinion.我一直在使用 react 一段时间,我发现 react 组件严重依赖于另一个组件,这在我看来不是一个好习惯。 My question is whether there is a way to work around this.
我的问题是是否有办法解决这个问题。
Let's look at an example below where Header component depends on Banner component让我们看下面的示例,其中 Header 组件依赖于 Banner 组件
import Banner from './../banner/Banner';
import HeaderInfo from './HeaderInfo';
class Header extends Component {
render() {
return (
<div id="header">
<Banner />
<HeaderInfo />
</div>
);
}
}
Suppose that there are 10 other components depending on Banner component, so if there are any changes to Banner component, for instance, adding a new prop, say, avatarUrl="/path/to/img" then Header component and all the 10 components would need to be altered to cater for the changes as follows假设有 10 个其他组件依赖于 Banner 组件,因此如果对 Banner 组件有任何更改,例如添加一个新的 prop,例如 avatarUrl="/path/to/img" 然后是 Header 组件和所有 10 个组件需要更改以适应以下更改
class Header extends Component {
render() {
return (
<div id="header">
<Banner avatarUrl="/path/to/img" /> // <--- new changes
<HeaderInfo />
</div>
);
}
}
This would lead to a nightmare when the number of components grows and changes need to be done in that situation.当组件数量增加并且在这种情况下需要进行更改时,这将导致噩梦。 The aforementioned way of importing and using components results in tight coupling among components which contradicts to a norm that there should be tight cohesion within a component and loose coupling among components.
上述引入和使用组件的方式导致组件之间的紧密耦合,这与组件内应该有紧密内聚和组件之间松散耦合的规范相矛盾。
I wonder if there's another way to connecting and using components that makes the dependence among component loose.我想知道是否有另一种连接和使用组件的方法可以使组件之间的依赖松散。
Thanks.谢谢。
If you are concerned about the states dependencies, both Redux & context API will be a good solution.如果您担心状态依赖关系,Redux 和上下文 API 将是一个很好的解决方案。 If you are talking about the de-coupling of components, render props will be the thing you want to check.
如果您正在谈论组件的解耦,那么渲染道具将是您想要检查的东西。
Currently if any props needs to be passed to Banner component.当前是否需要将任何道具传递给 Banner 组件。 Its has to be passed from Header component.
它必须从 Header 组件传递。 This is using local state.
这是使用本地状态。
But to overcoming this issue, we have redux store.但是为了克服这个问题,我们有 redux store。 Everything is stored in redux store.
一切都存储在 redux store 中。 And when any value is needed in banner component.
当横幅组件中需要任何值时。 Instead of passing from Header component, we can direct access from Banner component itself.
我们可以直接从 Banner 组件本身访问,而不是从 Header 组件传递。 (connecting to the store from Banner component).
(从 Banner 组件连接到商店)。
Reference: https://redux.js.org/basics/store参考: https : //redux.js.org/basics/store
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.