首页 > 解决方案 > Apollo 中具有本地状态的变量返回数据

问题描述

所以,我Apollo-link-state用来在 React GraphQL 应用程序中管理我的本地状态,我试图在全局状态中存储不同路径的列排序值,所以例如,如果你在/people,你可能会按firstName. 理想情况下,我只需查询getSorting,传入path并获取columnand 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 中有一个开关,然后只返回columnand 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 应该如何工作的?

标签: reactjsgraphqlapolloreact-apollographql-js

解决方案


您可以在使用apollo-link-state. 这意味着您的基础数据可以只是一组首选项对象,每个首选项对象都具有三个属性:和column,并且您的自定义解析器可以根据路径找到正确的对象。directionpath

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

显然,如果你走这条路,你需要相应地更新你的突变。


推荐阅读