Hello StackOverflow community,

在相当长的一段时间里我使用重构来创建一个 higher order component ,这将使用重构 branch 来显示Spinner组件"isFetching"是真还是组件如果它是假的 .

问题是我在redux存储中持有“isFetching”标志,我想从那里使用标志,而不是从组件状态,因此其他组件将知道另一个组件正在获取数据 .

我的“withLoader”HOC如下所示:

const withLoader = branch(
  ({ isFetching }) => isFetching,
  renderComponent(Spinner)
)

这个HOC的实际用法如下:

const Component = ({ cover }) => (
  <div>
    <img src={cover.url} />
  </div>
)

const mapStateToProps = (state) => ({
  entity: entitySelector(state),
  isFetching: isFetchingSelector(state),
})

export default compose(
  connect(mapStateToProps, { fetchData }),
  lifecycle({
    componentDidMount() {
      const { fetchData, match: { params } } = this.props
      fetchData(params.id)
    }
  }),
  withLoader
)(Component)

根据分支文档,如果未提供“right”,则在测试通过时将呈现包装的组件 .

数据树是标准化的,这意味着我的reducer导出了以下组合的reducers:

byId:

const byId = (state = {}, action) => {
  if (!action.payload) return state
  const { entities } = action.payload

  if (!entities || !entities.hasOwnProperty('entityName')) return state
  return merge(state, entities.entityName)
}

allIds:

const allIds = (state = [], action) => {

  switch (action.type) {
    case REQUEST_ENTITY_SUCCESS:
      return action.payload.result
    default:
      return state
  }

}

and the last one isFetching:

const isFetching = (state = false, action) => {
  switch (action.type) {
    case REQUEST_ENTITY:
      return true
    case REQUEST_ENTITY_SUCCESS:
    case REQUEST_ENTITY_FAILURE:
      return false
    default:
      return state
  }
}

到目前为止,我知道componentDidMount生命周期在组件实际呈现后触发fetchData,因此它会抛出错误,因为cover是未定义的 . 就像我说的:主要是在web中我可以找到涉及组件状态的解决方案,但是如果我的“isFetching”指示器存储在redux存储中,我在这种情况下看不到使用组件状态的任何意义 .

我的问题是如何在不使用组件内部状态的情况下使用isFetching从redux状态正确地使我的“withLoader”HOC功能正常?

抱歉有点冗长的问题,但我想让一切都清楚,并覆盖真实的代码 .