如何将 graphQL 查询变量传递给装饰过的 React 组件

How to pass graphQL query variable into a decorated react component

有谁知道将查询变量添加到 apollo 的正确方法是什么?如果我手动添加书名字符串而不是传入 $name 查询变量,我可以获得以下代码,但是一旦我添加它并尝试通过 propTypes 中的选项传递名称变量, Invariant Violation: The operation 'data' wrapping 'BookPage' is expecting a variable: 'name' but it was not found in the props passed to 'Apollo(BookPage)'

我直接从 reactQL 包中提取了装饰器的语法,所以我知道它比其他示例有更多的语法糖,但它对查询仍然有效,对吗?

const query = gql`
  query ($name: String!){
    bookByName(name: $name) {
      id
    }
}
`;

@graphql(query)
class BookPage extends React.PureComponent {
  static propTypes = {
    options: (props) => { return { variables: { name: "Quantum Mechanics"}}},
    data: mergeData({
      book:
        PropTypes.shape({
          id: PropTypes.string.isRequired,
        }),
    }),
  }

  render() {
    const { data } = this.props;
    if (data.loading) {
      return <p>Loading</p>
    }
    const { bookByName } = data;
    const book = bookByName;

    return (
      <p>book.id</p>
    );
  }
}

export default BookPage;

@graphql 装饰器有第二个参数,您可以在其中定义查询或变更的选项。

类似于config中的选项定义。

所以在你的情况下它可能看起来像:

const query = gql`
  query ($name: String!){
    bookByName(name: $name) {
      id
    }
}
`;

@graphql(query, {
  options: (ownProps) => ({
    variables: {
      name: ownProps.bookName // ownProps are the props that are added from the parent component
    },
  })})
class BookPage extends React.PureComponent {
  static propTypes = {
    bookName: PropTypes.string.isRequired,
    data: mergeData({
      book:
        PropTypes.shape({
          id: PropTypes.string.isRequired,
        }),
    }),
  }

  render() {
    const { data } = this.props;
    if (data.loading) {
      return <p>Loading</p>
    }
    const { bookByName } = data;
    const book = bookByName;

    return (
      <p>book.id</p>
    );
  }
}

export default BookPage;