【问题标题】:How to pass graphQL query variable into a decorated react component如何将 graphQL 查询变量传递到修饰的反应组件中
【发布时间】:2017-10-30 09:04:39
【问题描述】:

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

【问题讨论】:

    标签: reactjs graphql react-apollo apollo-client


    【解决方案1】:

    @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;

    【讨论】:

    • 我试图将该选项配置放入 propTypes 而不是装饰器,您的方式效果很好。谢谢!
    猜你喜欢
    • 2021-08-29
    • 2018-02-27
    • 2017-05-15
    • 2019-10-16
    • 2022-01-24
    • 2020-11-30
    • 2020-11-12
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多