reactjs - 如何将 graphQL 查询变量传递到装饰的 React 组件中

标签 reactjs graphql react-apollo apollo-client

有谁知道向 apollo 添加查询变量的正确方法是如何从 React 中获得的?如果我手动添加书名字符串而不是传入 $name 查询变量,我可以让以下代码正常工作,但是一旦我添加它并尝试通过propTypes 中的选项,不变违规:包装“BookPage”的操作“data”需要一个变量:“name”,但在传递给“Apollo(BookPage)”的 props 中找不到该变量

我直接从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;

关于reactjs - 如何将 graphQL 查询变量传递到装饰的 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44252916/

相关文章:

android - AppSync 和推送通知

graphql - 突变后,如何跨 View 更新受影响的数据?

graphql - 如何正确地将变量传递给 apollo useQuery?

javascript - 如何在将按钮(Material UI)动态设置为禁用后更改其颜色?

javascript - 无法对 Gatsby 站点中 Ant Design Table 中的列进行排序

reactjs - redux-saga 的单元测试抛出错误 : runSaga must be called on an iterator

python - 如何在python graphene中处理带参数的查询

javascript - 无法从 ApolloClient 中的 localStorage 检索更新的 token

javascript - 如何在点击 react 后播放 mp3?

javascript - 尝试登录时出现 React-native、Firebase 网络错误