本文介绍了如何将变量传递给 GraphQL 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 React-Apollo 中有以下 GraphQL 查询

Lets assume I have the following GraphQL query in React-Apollo

const CurrentUserForLayout = gql`
  query CurrentUserForLayout($avatarID: Int!) {
    currentUser {
      avatar_url(avatarID: $avatarID)
    }
  }
`;

const ProfileWithData = graphql(CurrentUserForLayout, {
  options: { variables: { avatarID: 1 } },
})(Profile);

现在,如果我想让我的 React 组件 Profile 更改头像 ID,

Now if I want to let my React component Profile change the avatarID,

我该怎么做?

我是 React 和 GraphQl 的新手,我不太了解这里的联系:

I am new to React and GraphQl and I do not really understand the connection here:

graphql(CurrentUserForLayout, {
      options: { variables: { avatarID: 1 } },
    })(Profile);

我真的需要另一个围绕 ProfileWithData 的父组件吗?将另一个 avatarID 传递给查询?但是如果这个 ID 是由 Profile 组件操作的,我该如何让 Parent 组件知道呢?

Do I really need another parent component around ProfileWithDatato pass another avatarID to the query? But what if the ID is manipulated by the Profile component, how do I let the Parent component know about that?

推荐答案

到目前为止,我知道两种可能的方法.

So far, I know two possible approaches to this.

第一个已经在问题中说明了.变量同时是 ProfileWithData 的道具.所以你需要找到一种方法来改变 props 并重新渲染组件.这通常是通过父组件实现的.所以通常你不会改变 ProfileWithData 里面的变量.此组件应仅用于显示目的.然而,这并不是说它不能做到.您可以将父组件的方法传递给子组件以操纵父组件的状态.这将重新渲染两个组件并使用新的道具/变量渲染 ProfileWithData.

The first one is already stated in the question. The variables are at the same time the props of the ProfileWithData. So you need to find a way to change the props and rerender the component. This is usually achieved with a parent component. So usually you do not change the variables inside of ProfileWithData. This component should be used only for display purposes. However, this does not say that it can't be done. You can pass the methods of your parent component to the child in order to manipulate the state of the parent. This will rerender both components and render the ProfileWithData with new props/variables.

第二种方法是从 ProfileWithData 组件内部进行查询.然后,您可以使用状态从组件内部操作变量.可以在此处

The second approach is to query from the inside of the ProfileWithData component. You can then manipulate the variables from the inside of the component with the state. A method to do this can be found here

您可以通过使用对 Apollo Client 的引用来实现withApollo 高阶组件,如此处所述:http://dev.apollodata.com/react/higher-order-components.html#withApollo

然后,您可以对传入的对象调用 client.query,如下所示:

Then, you can call client.query on the passed in object, like so:

 class MyComponent extends React.Component {
      runQuery() {
        this.props.client.query({
          query: gql`...`,
          variables: { ... },
        });
      }

      render() { ... }
    }

    withApollo(MyComponent);

这篇关于如何将变量传递给 GraphQL 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:55