为什么回调(或 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/