reactjs - 为什么要在React组件的props中传递回调而不是使用react-redux的connect?

标签 reactjs redux

为什么回调(或 redux 的调度)通常在组件的 props 中传递,而不是总是使用 React-Redux 连接函数?

调度(或调度中包装的函数)作为 Prop :

// somewhere.js, calling Component in JSX with onButtonClick as props
<Component onButtonClick={someFunction}/>

// component.js
const Component = ({onButtonClick}) => <Button onClick={onButtonClick}>{'do something'}</Button>

对比

连接功能:

// somewhere.js, calling Component in JSX without giving props
<Component/>

// component.js
const Component = ({onButtonClick}) => <Button onClick={onButtonClick}>{'do something'}</Button>
const mapDispathToProps = (dispatch, ownProps) => {
   return {
            onButtonClick: dispatch(someFunction)
          }
}
connect(mapDispathToProps)(Component)

最佳答案

区别在于“演示”组件和“容器”组件,以前也称为智能组件和dumb组件。容器组件是您“连接”的组件,而演示组件是刚刚接收 props 的组件。

我将链接到 this Medium article作者:Dan Abramov,redux 的创建者。

引用福利部分:

  • Better separation of concerns. You understand your app and your UI better by writing components this way.
  • Better reusability. You can use the same presentational component with completely different state sources, and turn those into separate container components that can be further reused.
  • Presentational components are essentially your app’s “palette”. You can put them on a single page and let the designer tweak all their variations without touching the app’s logic. You can run screenshot regression tests on that page.
  • This forces you to extract “layout components” such as Sidebar, Page, ContextMenu and use this.props.children instead of duplicating the same markup and layout in several container components.
<小时/>

根据我个人的经验,强制自己使用这种风格确实可以让我的组件更加“理智”并且更容易理解/维护。欢迎您不使用这种风格,但是当您遇到问题时,您可能需要重构以使用这种更好地分离关注点的方法。

如果我要在没有 Dan 帮助的情况下进行总结,我会这样说:到处连接会使组件中每个 prop 的来源变得困惑。如果您强制自己仅在非常特定的位置进行连接(在我的项目中,我倾向于在页面级别和根级别进行连接),那么您将始终知道事情来自哪里,这有助于在出现问题时进行调试。

关于reactjs - 为什么要在React组件的props中传递回调而不是使用react-redux的connect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776817/

相关文章:

node.js - npm 安装@types/.../node_modules/react

reactjs - 错误 "JSX element type ' .. .' does not have any construct or call signatures"是什么意思?

javascript - React-Native BackHandler 总是在 Android 中关闭 App(硬件回退)

Redux - 如何区分卸载的内容和后端不存在的内容?

javascript - 如果使用 fetch 从服务器检索,则未设置 Redux 初始状态

typescript - 如何使用 Typescript 在 Redux reducer 函数内实现详尽的 switch 语句?如何处理 Redux 的内部 @@redux 操作

javascript - 当我使用 REACT/REDUX 创建新帖子时,API 会刷新并且之后不允许新帖子

ios - 在节点模块中对 native 重建 .bin 文件夹使用react

redux - 处理 Redux Store 数据中的依赖关系

css - 覆盖 React 组件