3

有谁知道向 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;
4

1 回答 1

4

装饰器有第二个参数,您可以在@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;

于 2017-05-30T06:04:30.873 回答