reactjs - Apollo 中具有本地状态的变量返回数据
问题描述
所以,我Apollo-link-state
用来在 React GraphQL 应用程序中管理我的本地状态,我试图在全局状态中存储不同路径的列排序值,所以例如,如果你在/people
,你可能会按firstName
. 理想情况下,我只需查询getSorting
,传入path
并获取column
and direction
。
因为 GraphQL 在设计上非常严格,所以我不得不编写一些相当难看的代码:
export const GET_SORTING_PREF = gql`
query GET_SORTING_PREF {
sortingPrefs @client {
assets {
column
direction
}
liabilities {
column
direction
}
reporting {
column
direction
}
people {
column
direction
}
companies {
column
direction
}
}
}
`
而在 Redux 中,我只是通过 up path
,在我的 reducer 中有一个开关,然后只返回column
and direction
。
实际的突变是这样写的(包括一个空返回,所以它不会抱怨):
export const setSortingPref = (_, {path, column, direction}, { cache }) => {
let { sortingPrefs } = cache.readQuery({
query: GET_SORTING_PREF
})
sortingPrefs[path] = {
column, direction
}
cache.writeQuery({
query: GET_SORTING_PREF,
data: { sortingPrefs }
})
return null;
}
有没有一种巧妙的方法可以让我传递path
并返回适当的值,而不需要所有这些愚蠢的重复,或者这就是 GraphQL 应该如何工作的?
解决方案
您可以在使用apollo-link-state
. 这意味着您的基础数据可以只是一组首选项对象,每个首选项对象都具有三个属性:和column
,并且您的自定义解析器可以根据路径找到正确的对象。direction
path
const stateLink = withClientState({
cache,
defaults: {
sortingPrefs: [
// defaults go here
]
},
resolvers: {
Query: {
// Note the difference in names between this and the default
sortingPref: (_, { path }, { cache }) => {
const query = `
query GetSortingPrefs {
sortingPrefs @client {
column
direction
path
}
}
`
const sortingPrefs = cache.readQuery({ query }).sortingPrefs
return sortingPrefs.find(p => p.path === path)
}
}
},
})
显然,如果你走这条路,你需要相应地更新你的突变。
推荐阅读
- node.js - 如何从 Google Text-to-Speech API(fs.writeFile vs createWriteStream)将文件写入 Firebase Storage?
- c# - 将 0 到 1 之间的 a 标准化为给定的最小值和最大值
- javascript - 将 Calendly 嵌入 React
- html - li元素内的div内的响应img?
- javascript - 使用jQuery的下拉隐藏显示
- javascript - 如何转义作为参数传递的字符串——无效的语法。参数列表后缺少 )
- visual-studio-code - 如何在 VSCode 中找到并覆盖 CREATE FOLDER 的键绑定?
- gitlab - gitlab-runner 无法在 Windows 7 上运行 gui 框架的测试打开
- bootstrap-accordion - 如何初始化动态添加到页面的引导控件?
- python - 读取多个文件,但找出我当前在哪个文件上