在高阶组件模式中,有没有一种方法可以让单个展示组件从两个 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
是空的。
是否可以从两个 HOC 获取 State 数据?
最佳答案
是的,更新您的 WithUserState
以传递 Prop 。
const WithUserState = WrappedComponent => {
return class extends Component {
state = {
userData: { userId: 1252748, userName: 'thomas' }
}
render() {
return <WrappedComponent {...this.props} userData={this.state.userData} />
}
}
}
关于javascript - 一个组件可以接收两个 HOC 的数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48014820/