0

我有一个名为 的组件PartyDetails,它需要通过 ajax 调用获取数据。我想Loading在 ajax 请求正在进行时显示一个组件。

问题是为了确定数据是否加载,我需要访问存储。这就是我的增强效果:

const enhance = compose(
    propSetter,
    lifecycleEnhancer,
    loading,
)

export default enhance(PartyDetails)

哪里propSetter是:

const propSetter = connect((state) => {
    const { party } = state
    const { dataLoaded } = party
    // for some reason state does not contain match, and I'm resorting to routing
    const { routing: {location: { pathname }}} = state
    const involvedPartyId = pathname.substring(pathname.lastIndexOf('/') + 1)
    return { dataLoaded, involvedPartyId }
}, {loadParty})

并且lifecycleEnhancer是:

const lifecycleEnhancer = lifecycle({
    componentDidMount() {
        this.props.loadParty(this.props.involvedPartyId)
    }
})

并且loading是(请注意,在这种情况下,dataLoaded来自前面connect已经完成的propSetter):

const loading = branch(
    ({dataLoaded}) => dataLoaded,
    renderComponent(connect(mapStateToProps, mapDispatchToProps)(PartyDetails)),
    renderComponent(Loading)
)

所以基本上,如果数据已被提取,我将使用第二个连接来获取PartyDetails.

recompose几天前我刚开始学习,但找不到适合我用例的示例。以上是我在阅读文档后得出的结论,以及在其他文章中找到的一些示例。

我正在做的事情是处理这个问题的好方法吗?这是否可以以更好的方式完成,也许不需要 2 个connect电话?

4

1 回答 1

0

您可以在一个连接中编写所有用于映射状态和分派到道具的逻辑:

export default compose(
  connect(
    state => {
      const { party } = state;
      const { dataLoaded } = party;
      const { routing: { location: { pathname } } } = state;
      const involvedPartyId = pathname.substring(pathname.lastIndexOf("/") + 1);

      // also put here your `mapStateToProps` code

      return { dataLoaded, involvedPartyId };
    },
    {
      loadParty
      // the same here, append `mapDispatchToProps` logic
    }
  ),
  lifecycle({
    componentDidMount() {
      this.props.loadParty(this.props.involvedPartyId);
    }
  }),
  branch(
    ({ dataLoaded }) => dataLoaded,
    renderComponent(PartyDetails),
    renderComponent(Loading)
  )
  // as `branch` is returning HOC, we need to provide empty component to it in
  // order to render whole component
)(createSink());
于 2017-10-12T12:08:00.533 回答