【问题标题】:Graphql query and ApolloGraphql 查询和 Apollo
【发布时间】:2018-10-19 09:59:16
【问题描述】:

我正在将 Apollo 与 React Native 一起使用,并且我正在执行查询以获取具有他的 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 是否有值并且该值已打印,我可以看到它。我做错了什么?

【问题讨论】:

    标签: graphql react-apollo


    【解决方案1】:

    您是否尝试过将变量名从 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>
     );
     }
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2018-03-02
      • 2021-07-04
      • 2020-11-04
      • 2021-07-04
      • 2018-06-13
      • 1970-01-01
      • 2018-02-01
      • 2019-12-06
      相关资源
      最近更新 更多