Graphql 查询和 Apollo

Graphql query and Apollo

我将 Apollo 与 React Native 结合使用,我正在查询以获取具有其 ID 的用户数据,该 ID 存储为 prop。 这是查询:

const GET_USER_DATA = gql`
 query User($id: ID!) {
  User(id: $id) {
   id
   name
  }
 }`;

然后这个代码

const User = ({ userId }) => {
console.log("User id: ", userId);
 return (
   <Query query={GET_USER_DATA} variables={{ userId }}>
     {({ loading, error, data }) => {
      if (loading) return <Text>Loading ...</Text>;
      if (error) return <Text>Error!: {error}</Text>;
       return (
       <Text>Text: {data}</Text>
     );
    }}
  </Query>
 );
 }

然后,如果道具存在,我添加这个:

 <User userId={this.props.data.loggedInUser.id} />

显示视图。 但是我得到这个错误

Error: GraphQL error: Variable '$id' expected value of type 'ID!' but 
value is undefined. Reason: Expected non-null value, found null.

我正在检查 userId 是否有值并且打印了该值,我可以看到它。我做错了什么?

您是否尝试过将变量名从 userId 更改为 id?

类似于:

const User = ({ id}) => {
console.log("User id: ", id);
 return (
   <Query query={GET_USER_DATA} variables={{ id }}>
     {({ loading, error, data }) => {
      if (loading) return <Text>Loading ...</Text>;
      if (error) return <Text>Error!: {error}</Text>;
       return (
       <Text>Text: {data}</Text>
     );
    }}
  </Query>
 );
 }

然后:

<User id={this.props.data.loggedInUser.id} />

将 userId 变量分配给 id 参数,例如:

const User = ({ userId }) => {
console.log("User id: ", userId);
 return (
   <Query query={GET_USER_DATA} variables={{ id: userId }}>
     {({ loading, error, data }) => {
      if (loading) return <Text>Loading ...</Text>;
      if (error) return <Text>Error!: {error}</Text>;
       return (
       <Text>Text: {data}</Text>
     );
    }}
  </Query>
 );
 }