在高阶组件模式中,是否有一种方法让单个展示组件从两个HOC接收状态?
例如:
const WithUserState = WrappedComponent => {
return class extends Component {
state = {
userData: { userId: 1252748, userName: 'thomas' }
}
render() {
return <WrappedComponent userData={this.state.userData} />
}
}
}
const WithCommentState = WrappedComponent => {
return class extends Component {
state = {
userComments: [{id: 0, comment: 'hello'}, {id: 1, comment: 'world'}]
}
render() {
return <WrappedComponent userComments={this.state.userComments} />
}
}
}
class UserAndComments extends Component {
render() {
return (
<section>
<code>user: {JSON.stringify(this.props.userData)}</code>
<hr />
<code>comments: {JSON.stringify(this.props.userComments)}</code>
</section>
)
}
}
我听说这是可能的,但我的谷歌搜索没有给我答案。我唯一能想到的是嵌套函数调用:
const ComonentWithUserAndComments = WithCommentState(WithUserState(UserAndComments))
这个方法不起作用:我只收到userData
,而userComments
为空。
WithCommentState(WithUserState(UserAndComments))
)仍然非常丑陋。这是实现此模式的典型方式吗?还是有更聪明的方法? - 1252748