使用 connect 和 withRouter 包装组件的顺序是否重要 [英] Does order in which you wrap component with connect and withRouter matter
问题描述
哪个 HOC 将包裹另一个.用多个 HOC 包装的顺序是否在反应中很重要?我已经创建了多个 HOC withSocket、withLoadingBar 等.我是否应该担心深度丑陋的嵌套,它会影响组件的性能吗?
Which HOC will wrap the other. Does the order of wrapping with multiple HOCs matter in react or not? I have created multiple HOCs withSocket, withLoadingBar etc etc. Should I be worry about deep ugly nesting, Will it make an impact on performance of component?
推荐答案
用多个 HOC 包装的顺序在反应与否中重要吗?
Does the order of wrapping with multiple HOCs matter in react or not?
你包装 HOC 的顺序很重要,因为 props 从一个 HOC 传递到它的子组件.考虑下面的例子
The order in which you wrap the HOCs matters because of the props that are passed on from one HOC to its child component. Consider the following example
const mapStateToProps(state, props) {
console.log(props.match);
return {
match: props.match
}
}
第一种情况:
withRouter(connect(mapStateToProps)(App));
在这种情况下,由于 withRouter
包装了 connect
,withRouter 提供的 props ie history, match etc
将是 在 connect 使用的 mapStateToProps
中可用.
In this case since the withRouter
wraps the connect
, the props provided by withRouter ie history, match etc
will be available in mapStateToProps
used by connect.
想想像这样的 HOC
Think of an HOC like
const MyComponent = connect(mapStateToProps)(App);
export default withRouter(MyComponent);
其中 withRouter
可以像
const withRouter = (Comp) => {
return class Something extends React.Component {
render() {
return <Comp match={this.context.router.match} />
}
}
..
}
因此在这种情况下,用 withRouter
包裹的 Comp
即 MyComponent
接收匹配道具,在上述情况下是connect
and so in this case, the Comp
i.e MyComponent
which is wrapped with withRouter
receives the match props, which in the above case is the component being wrapped by connect
第二种情况:
connect(mapStateToProps)(withRouter(App));
在这种情况下,由于connect包装了withRouter,withRouter
提供的props ie history, match etc
在mapStateToProps
由 connect
使用,如果它们不是由父级提供的.
In this case since the connect wraps the withRouter, the props provided by withRouter
ie history, match etc
will not be available in mapStateToProps
used by connect
if they are not provided by the parent.
我应该担心深度丑陋的嵌套吗?
Should I be worry about deep ugly nesting?
如果一个 HOC 提供的 props 被另一个使用,你应该只担心它.假设你直接在基础组件内部使用从 HOC 传递下来的 props,你就不需要担心顺序
you should only worry about it if the props provided by one HOC is being used by another. Say if you use passed down props from HOC directly inside the base component, you won't need to worry about the order
是否会影响组件的性能?
Will it make an impact on performance of component?
使用 HOC 的顺序不影响组件性能
The order of using HOC doesn't affect a components performance
检查下面的代码和框以获取示例
Check the below codesandbox for an example
这篇关于使用 connect 和 withRouter 包装组件的顺序是否重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!