管理依赖状态

时间:2018-04-27 14:25:34

标签: reactjs redux

我有以下状态:

{
    programmeCodes,  // generated from asynch resource
    programmeColors   // depends on programmeCodes
}

以及asynch资源的以下操作:

export const REQUEST_PROGRAMME_CODES = 'REQUEST_PROGRAMME_CODES'
export const RECEIVE_PROGRAMME_CODES = 'RECEIVE_PROGRAMME_CODES'

function requestProgrammeCodes() {
  return {
    type: REQUEST_PROGRAMME_CODES,
  }
}

export function fetchProgrammeCodes() {
  return function (dispatch) {
    dispatch(requestProgrammeCodes())

    return api.fetchProgrammes()
      .then(
        response => response,
        error => console.log('An error occurred.', error)
      )
      .then(json =>
        dispatch(receiveProgrammeCodes(json))
      )
  }
}

function shouldFetchProgrammeCodes(state) {
  const codes = state.programmeCodes.codes.length > 0

  if (!codes) {
    return true
  } else if (codes.isFetching) {
    return false
  } else {
    return codes.didInvalidate
  }
}

export function fetchProgrammeCodesIfNeeded() {
  return (dispatch, getState) => {
    if (shouldFetchProgrammeCodes(getState())) {
      // Dispatch a thunk from thunk!
      return dispatch(fetchProgrammeCodes())
    } else {
      return Promise.resolve()
    }
  }
}

'programmeCodes'是生成'programmeColors'所需的依赖项。 我喜欢(有良好做法)能够在React组件中请求'programmeColors',而不必担心是否已收到programmeCodes。

如何为'programmeColors'编写动作以实现上述目标?

0 个答案:

没有答案