我正在使用 React Apollo 查询我的数据存储中的所有记录,以便我可以在搜索过滤器中创建选择。
我使用的重要数据库模型是Report
。
Report
包含doorType
、doorWidth
、glass
和manufacturer
字段。
目前,当查询响应时,我将 allReports
传递给多个dumb组件,这些组件通过数组并仅获取唯一的项目来制作一个可选列表,就像这样..
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
组件中返回时,我想分派(dispatch)一个 Action 。这是查询...
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
组件中执行上面的代码,但它保存在商店中,所以我不需要重新运行查询用户返回页面。
很少有数据会更新,侧边栏需要更改。
希望有一个使用 graphql
函数的 props
参数的解决方案。我觉得可以从 ownProps
获取数据,然后可以在此处分派(dispatch)一个 Action ,但数据可能会出错或正在加载,这会破坏渲染。
编辑:
查询:
query ($isPublished: Boolean!){
allReports(filter:{
isPublished: $isPublished
}) {
id
oldId
dbrw
core
manufacturer {
id
name
}
doorWidth
doorType
glass
testBy
testDate
testId
isAssessment
file {
url
}
}
}
最佳答案
虽然这个答案解决了问题的具体问题,但更普遍的问题——根据查询结果在何处分派(dispatch) Redux 操作——仍然不清楚。到目前为止,似乎还没有最佳实践。
关于javascript - 在 React Apollo 查询返回后调度 Redux 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236519/