首页 文章

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

提问于
浏览
4

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

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

Report 具有 doorTypedoorWidthglassmanufacturer 个字段 .

目前,当查询响应时,我将 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
})

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

我想在查询在 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
)

Redux操作 setDoorWidths 基本上执行 SidebarFilter 组件中的上述代码,但如果用户返回页面,则需要重新运行查询 .

数据更新非常罕见,侧栏需要更改 .

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

编辑:

查询:

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

2 回答

  • 4

    虽然这个答案解决了问题的具体问题,但更一般的问题 - 基于查询结果发送Redux操作的位置 - 仍然不清楚 . 到目前为止,似乎还没有最好的做法 .

  • 2

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

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

    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,
    })
    

    可能需要修改上述内容,具体取决于 data 的结构 . data has some handy props on it可以让您检查查询是否正在加载( data.loading )或有错误( data.error ) . 上面的例子已经防止向你的孩子发送一个未定义的道具,但如果你愿意,你可以很容易地将这些属性合并到你的逻辑中 .

相关问题