在高阶组件模式中,是否存在单个表示组件可以从两个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
为空。
答案 0 :(得分:1)
是的,请更新您的WithUserState
以传递道具。
const WithUserState = WrappedComponent => {
return class extends Component {
state = {
userData: { userId: 1252748, userName: 'thomas' }
}
render() {
return <WrappedComponent {...this.props} userData={this.state.userData} />
}
}
}