当前位置 : 主页 > 网页制作 > React >

reactjs – 为什么要在React组件的道具中传递回调而不是使用react-redux的连接?

来源:互联网 收集:自由互联 发布时间:2021-06-15
为什么回调(或redux的调度)在组件的道具中传递而不是总是使用react-redux连接函数是常见的? 作为道具的调度(或调度包裹的功能): // somewhere.js, calling Component in JSX with onButtonClick as prop
为什么回调(或redux的调度)在组件的道具中传递而不是总是使用react-redux连接函数是常见的?

作为道具的调度(或调度包裹的功能):

// 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)
不同之处在于“表现”和“容器”组件,以前也称为智能和哑组件.容器组件是您“连接”的组件,而表示组件是刚接收道具的组件.

我将由redux的创建者Dan Abramov链接到this Medium article.

引用福利部分:

  • 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帮助的情况下进行总结,我会这样说:连接到整个地方会让你对组件中每个道具的来源感到困惑.如果你强迫自己只在非常特定的地方连接(在我的项目中,我倾向于在页面级别和根级别连接),那么你总是会知道事情的来源,这有助于在出现问题时进行调试.

网友评论