gpt4 book ai didi

javascript - React-Redux:我是否必须对单个组件树中的所有组件使用 connect() 和映射状态/调度?有没有办法只做一次?

转载 作者:行者123 更新时间:2023-11-28 14:14:35 24 4
gpt4 key购买 nike

所以基本上我有一个带有单个组件树的应用程序。 App 作为父级,然后从那里下降。最初,所有状态显然都是从父组件 App 集中的,就像通常一样,然后状态通过 props 传递给每个组件。我们都知道随着组件树变得越来越大,这会很麻烦。

我正在研究 React-Redux,只是好奇我是否总是必须使用 connect(),然后分别创建一个 mapStateToPropsmapDispatchToProps > 对于我的每个组件(包括子组件)?有没有一种一次性的方法可以做到这一点?我的许多组件是否可以只访问整个存储,而不需要将每个状态/调度一一映射到 Prop ,我发现这重复且耗时?

我有 Vue-Vuex 背景(尽管我的 Vuex 经验有限),React-Redux 只是一个完全不同的球蜡,在我看来,如果不是更复杂的话。

最佳答案

根据 Redux FAQ entry on "Should I connect all my components, or just one?" :

Early Redux documentation advised that you should only have a few connected components near the top of your component tree. However, time and experience has shown that such a component architecture generally requires a few components to know too much about the data requirements of all their descendants, and forces them to pass down a confusing number of props.

Emphasizing “one container component at the top” in Redux examples was a mistake. Don't take this as a maxim. Try to keep your presentation components separate. Create container components by connecting them when it's convenient. Whenever you feel like you're duplicating code in parent components to provide data for same kinds of children, time to extract a container. Generally as soon as you feel a parent knows too much about “personal” data or actions of its children, time to extract a container.

事实上,基准测试表明,连接的组件越多通常会比连接的组件越少带来更好的性能。

一般来说,尝试在可理解的数据流和组件的责任范围之间找到平衡。

关于javascript - React-Redux:我是否必须对单个组件树中的所有组件使用 connect() 和映射状态/调度?有没有办法只做一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58078467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com