【问题标题】:How to pass data from react component to Apollo graphql query?如何将数据从反应组件传递到 Apollo graphql 查询?
【发布时间】:2018-02-27 10:57:42
【问题描述】:

我正在使用 react-native 和 apollo/graphql 开发一个应用程序。

在这种情况下,我想做的是在我的组件中进行计算(在这种情况下扫描条形码),然后将结果传递给我的 graphql 查询,以便它可以使用条形码访问我们的后端 api 并返回结果。

我已经在 apollo docs 和 google 中搜索了几个小时,但我不知所措。

这是我想要做的事情的要点:

class ScanBookScreen extends Component {

  state = {
    hasCameraPermission: null,
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <BarCodeScanner
          onBarCodeRead={// pass this to the query down below} <-----
        />
      </View>
    );
  }
}

const lookupTextbooksQuery = gql`
  query lookupTextbooks($query: String) {
    lookupTextbooks (query: $query, limit: 1) {
      totalItems
      textbooks {
        id
        title
        description
      }
    }
  }
`;

export default graphql(lookupTextbooksQuery, {
    options: { variables: { query: // This is the part that needs to come from the component somehow} }, <----

})(ScanBookScreen);

【问题讨论】:

    标签: reactjs react-native graphql react-apollo


    【解决方案1】:
    render() {
        let { refetch } = this.props.data
        return (
          <View style={{ flex: 1 }}>
            <BarCodeScanner
             onBarCodeRead={query => refetch({ query })} 
            />
          </View>
        );
    }
    

    你会做这样的事情。如果你想将组件的 props 传递给初始查询,你可以这样做:

    options: props =&gt; ({ variables: { query: props.query } })

    http://dev.apollodata.com/core/apollo-client-api.html#ObservableQuery.refetch

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2017-10-30
      • 2018-11-27
      • 2018-06-03
      • 2018-08-16
      • 2020-01-25
      • 2017-04-22
      • 2021-08-29
      • 2020-10-28
      相关资源
      最近更新 更多