javascript - 如何使用 React 高阶函数最大化可组合性?
问题描述
我参考了React官方教程的这一部分(Convention: Maximizing Composability):
// connect is a function that returns another function
const enhance = connect(commentListSelector, commentListActions);
// The returned function is a HOC, which returns a component that is connected
// to the Redux store
const ConnectedComment = enhance(CommentList);
我们应该如何实现 connect() 函数?
解决方案
从概念上讲,HOC 连接是这样的:
function connect(mapStateToProps, mapDispatchToProps) {
return function (WrappedComponent) {
return class extends React.Component {
render() {
return (
<WrappedComponent
{...this.props}
/>
)
}
}
}
}
你怎么看,它是一个返回另一个函数的函数。
第一次调用 connect 得到 2 个参数
const enhance = connect(commentListSelector, commentListActions);
在第二个它得到我们在连接函数中返回的组件
const ConnectedComment = enhance(CommentList);
但不仅是组件,我们还使用从 redux 获得的新道具返回 connect - 所以这是如何从 redux 获取数据的方法,请查看更详细的示例(如果这对您来说还不够,您可以查看上面评论中的链接):
function connect(mapStateToProps, mapDispatchToProps) {
return function (WrappedComponent) {
return class extends React.Component {
render() {
return (
<WrappedComponent
{...this.props}
{...mapStateToProps(store.getState(), this.props)}
{...mapDispatchToProps(store.dispatch, this.props)}
/>
)
}
}
}
}
对我来说更有用和方便的是 react-hook 模式,检查 useSelector 和 useDispatch 方法从 redux 组件获取数据以进行反应。它更简单,连接了遗留方法,并且仅对 Class 组件有用。
推荐阅读
- python - 我已经在 python 中导入了一个 excel 文件,我正在尝试将第 7 行作为起始列。我需要隐藏前 6 行我该怎么做?
- html - 基本硒无法按类查找元素
- vpn - Openconnect 连接但无法实际访问 vpn
- ubuntu - 无法在 Microk8s 上使用 MutatingAdmissionWebhook 注入环境变量
- sharepoint - SharePoint 流:收集初始批准,然后在日期/时间延迟并发送所有最终批准
- xml - 基于属性值的 XSLT 2.0 group-adjacent
- selenium - 如何减慢 Selenium WebDriver 测试的执行速度
- javascript - 如何从反应打字稿中构建单个入口点?
- database - 使用 EF 核心从另一个表列生成主键
- javascript - 从普通的javascript调用角度组件函数