我有一个将字符串(userToFetch
)作为变量传递给参数化查询的组件。该组件如下所示:
// pages/index.jsx import React from 'react'; import { useQuery } from '@apollo/react-hooks'; import gql from 'graphql-tag'; const GET_USERS = gql` query users ($limit: Int!, $username: String!) { users (limit: $limit, where: { username: $username }) { username firstName } } `; const Home = () => { const userToFetch = 'jonsnow'; const { loading, error, data, } = useQuery( GET_USERS, { variables: { limit: 2, username: userToFetch }, notifyOnNetworkStatusChange: true, }, ); if (loading) { returnLoading...
; } if (error) { returnError: {JSON.stringify(error)}
; } return (); }; export default Home;{data.users.map(user => { return
- {user.username} {user.firstName}
; })}
这就是我配置Apollo客户端的方式:
// /apollo-client.js import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import withApollo from 'next-with-apollo'; import { createHttpLink } from 'apollo-link-http'; import fetch from 'isomorphic-unfetch'; const GRAPHQL_URL = 'https://dev.schandillia.com/graphql'; const link = createHttpLink({ fetch, // Switches between unfetch & node-fetch for client & server. uri: GRAPHQL_URL }); // Export a HOC from next-with-apollo // Docs: https://www.npmjs.com/package/next-with-apollo export default withApollo( // You can get headers and ctx (context) from the callback params // e.g. ({ headers, ctx, initialState }) ({ initialState, ctx }) => { console.log('initialState', initialState); console.log('ctx', ctx); return new ApolloClient({ link: link, cache: new InMemoryCache() // rehydrate the cache using the initial data passed from the server: .restore(initialState || {}) }) } );
该数据库是以下各项的集合users
:
"users": [ { "username": "negger", "firstName": "Arnold", "lastName": "Schwarzenegger" }, { "username": "jonsnow", "firstName": "Jon", "lastName": "Snow" }, { "username": "tonystark", "firstName": "Tony", "lastName": "Stark" } ] }
现在,尽管这应该工作(当我在位于https://dev.schandillia.com/graphql的 graphql游乐场中运行查询时,它确实可以工作),但代码运行时就好像该where
子句不存在一样!它只是返回所有结果,就像正在运行的查询是:
users { _id username firstName }
为了重现该问题,请访问https://www.schandillia.com。该页面应该显示仅包含一个由匹配的username-firstName值组成的元素的列表:jonsnow Jon
但是它返回两个条目,negger Arnold
和jonsnow Jon
(指定limit
但完全忽略where
)。现在,使用https://dev.schandillia.com/graphql中jonsnow
的where
参数运行相同的查询:
{ users(where: { username: "jonsnow" }) { _id username firstName } }
结果将完全符合预期:
{ "data": { "users": [ { "_id": "5d9f261678a32159e61018fc", "username": "jonsnow", "firstName": "Jon", } ] } }
我在俯视什么?
PS:该仓库已在https://github.com/amitschandillia/proost/tree/master/apollo-nextjs上提供了参考。
更新:为了跟踪根本原因,我尝试在中记录一些值apollo-client.js
:
console.log('initialState', initialState);
奇怪的是,输出显示正确的查询以及要传递的变量,但结果错误:
... ROOT_QUERY.users({"limit":2,"where":{"username":"jonsnow"}}).0: firstName: "Arnold" username: "negger" __typename: "UsersPermissionsUser" ...
更新:这是我的Apollo客户端开发人员工具中结果的屏幕截图: