一个组件能从两个高阶组件接收数据吗?

3

在高阶组件模式中,是否有一种方法让单个展示组件从两个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为空。

是否可以从两个高阶组件(HOCs)获取状态(state)数据?

codesandbox

1个回答

1

是的,请更新您的WithUserState以传递props。

const WithUserState = WrappedComponent => {
  return class extends Component {
    state = {
      userData: { userId: 1252748, userName: 'thomas' }
    }
    render() {
      return <WrappedComponent {...this.props} userData={this.state.userData} />
    }
  }
}

啊哈。虽然这与我上面的内容配合使用,但嵌套语法(WithCommentState(WithUserState(UserAndComments)))仍然非常丑陋。这是实现此模式的典型方式吗?还是有更聪明的方法? - 1252748
在我看来,这可能是除了使用Redux(或类似的替代品)之外最好的方法。 - patrick
2
我使用recompose来组合高阶组件:https://github.com/acdlite/recompose#composition - brub
如果这个回答解决了你的问题,请不要忘记标记它!:D - patrick
抱歉,是的,对此感到抱歉! - 1252748
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接