问题
In my previous projects, I usually have only one connect(mapStateToProps, mapDispatchToProps)(App). But when I check the official example today, I find there is almost one connect() for each container.
what are the benefits to have multiple connect()?
回答1:
Imagine a Redux version of Stack Overflow's Q&A page. You'd have quite a few components: the question and its votes, answers and their votes, the Markdown editor for additional answers, the profile link at the top, and related and network questions on the right. The corresponding Redux store could have sub-objects for the active question, active answers, related questions, user profile, and Markdown editor.
You could use a single top-level connect, as you mentioned, but connecting each component individually offers performance and encapsulation:
- A single top-level
connectmeans that the top-levelAppgets re-rendered whenever any Redux store value changes, then it has to pass down those props to each of its child components (which either have to re-render or checkshouldComponentUpdate). If youconnecteach component separately, then, e.g., when you type something in the Markdown editor and update the editor's slice of the store, only the Markdown editor re-renders. - A single top-level
connectmeans that the top-levelAppneeds to know everything under it, so that it can pass down all of the needed props and events itself. Individualconnects offer encapsulation: the profile bar canconnectto the props and action creators that it needs, and higher-level components don't have to know or care about the details.
来源:https://stackoverflow.com/questions/44297383/in-redux-there-is-one-connect-for-each-container