在 React Apollo 查询返回后调度 Redux 操作

Jam*_*e B 5 javascript reactjs graphql redux react-apollo

我正在使用 React Apollo 查询数据存储中的所有记录,以便我可以在搜索过滤器中创建选择。

我使用的重要数据库模型是Report.

ReportdoorTypedoorWidthglassmanufacturer领域。

目前,当查询响应时,我将传递allReports给多个通过数组的哑组件,并仅获取唯一项以制作可选列表,就像这样..

const uniqueItems = []

items.map(i => {
  const current = i[itemType]

  if (typeof current === 'object') {
    if (uniqueItems.filter(o => o.id !== current.id)) {
      return uniqueItems.push(current)
    }
  } else if (!uniqueItems.includes(current)) {
    return uniqueItems.push(current)
  }

  return
})
Run Code Online (Sandbox Code Playgroud)

显然,这段代码并不漂亮,而且有点矫枉过正。

当查询在我的SidebarFilter组件中返回时,我想分派一个动作。这是查询...

const withData = graphql(REPORT_FILTER_QUERY, {
  options: ({ isPublished }) => ({
    variables: { isPublished }
  })
})

const mapStateToProps = ({
  reportFilter: { isPublished }
  // filterOptions: { doorWidths }
}) => ({
  isAssessment
  // doorWidths
})

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      resetFilter,
      saveFilter,
      setDoorWidths,
      handleDoorWidthSelect
    },
    dispatch
  )

export default compose(connect(mapStateToProps, mapDispatchToProps), withData)(
  Filter
)
Run Code Online (Sandbox Code Playgroud)

Redux 操作setDoorWidths基本上在SidebarFilter组件中执行上面的代码,但它保存在商店中,因此如果用户返回页面,我不需要重新运行查询。

数据更新和侧边栏需要更改的情况非常罕见。

希望有一个使用函数props参数的解决方案graphql。我觉得可以从中获取数据ownProps,然后可以在此处调度操作,但数据可能会出错或正在加载,这会破坏渲染。

编辑:

询问:

query ($isPublished: Boolean!){
  allReports(filter:{
    isPublished: $isPublished
  }) {
  id
  oldId
  dbrw
  core
  manufacturer {
    id
    name
  }
  doorWidth
  doorType
  glass
  testBy
  testDate
  testId
  isAssessment
  file {
    url
  }
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*den 2

在我看来,由于 Apollo 已经为您将查询结果缓存在您的商店中(或者单独的商店,如果您没有集成它们),因此调度一个仅将数据存储在您的商店中的操作是多余的店铺。

如果我正确理解您的问题,您的意图是仅过滤传入数据一次,然后将结果作为道具发送给组件的无状态子级。在 HOC 的配置中使用 props 属性是正确的graphql。为什么不直接做这样的事情:

const mapDataToProps = ({ data = {} }) => {
  const items = data
  const uniqueItems = []

  // insert your logic for filtering the data here

  return { uniqueItems } // or whatever you want the prop to be called
}

const withData = graphql(REPORT_FILTER_QUERY, {
  options: ({ isPublished }) => ({
    variables: { isPublished }
  }),
  props: mapDataToProps,
})
Run Code Online (Sandbox Code Playgroud)

上面的内容可能需要根据data实际的结构进行修改。data 它有一些方便的道具,可以让您检查查询是否正在加载(data.loading)或有错误(data.error)。上面的示例已经防止向您的孩子发送未定义的 prop,但是如果您愿意,您可以轻松地将这些属性合并到您的逻辑中。