【问题标题】:How to pass in prop from react-router / url to graphql query?如何将 prop 从 react-router / url 传递到 graphql 查询?
【发布时间】:2017-08-28 11:35:02
【问题描述】:

如果我有这样的路线:

<Route path="/something/:id" component={Something} />

我有一个这样的查询

const somethingQuery = gql`query getSomething {
  something(id:1) {
    name
  }
}`

export default compose(
  graphql(somethingQuery),
)(Something)

现在这总是将something1id 拉在一起。

如何将url参数:id传入查询id

【问题讨论】:

    标签: reactjs react-apollo apollo-client


    【解决方案1】:

    我认为您需要为选项使用箭头功能

    const somethingQuery = gql`query getSomething {
      something(id:$id) {
        name
      }
    }`
    
    const somethingWithData = graphql(somethingQuery, {
      options: (ownProps) => {
        variables: {
          id: ownProps.params.id
        }
      }
    })(Something)
    
    export default somethingWithData
    

    另外,对我来说,参数可以在 props.match 中找到,所以它看起来像这样(在 React Router 4 中)。哦,我还将($id: ID!) 参数传递给查询

    const somethingQuery = gql`query getSomething($id: ID!) {
      something(id:$id) {
        name
      }
    }`
    
    const somethingWithData = graphql(somethingQuery, {
      options: (ownProps) => {
        variables: {
          id: ownProps.match.params.id
        }
      }
    })(Something)
    
    export default somethingWithData
    

    【讨论】:

    • 应该是公认的答案,为我修好了!还有关于 React router 4 的注释很棒。
    【解决方案2】:

    要为 id 引入变量,您应该对查询变量使用 GraphQL 表示法。首先将$id参数添加到查询参数中,并将其分配给id参数

    const somethingQuery = gql`query getSomething {
      something(id:$id) {
        name
      }
    }`
    
    const somethingWithData = graphql(somethingQuery, {
      options: (ownProps) {
        variables: {
          id: ownProps.params.id
        }
      }
    })(Something)
    
    export default somethingWithData
    

    您也可以像在示例中那样在导出中使用 compose,但我喜欢这种方式 ;)

    【讨论】:

    猜你喜欢
    • 2020-01-25
    • 2018-11-27
    • 2019-01-24
    • 1970-01-01
    • 2018-04-26
    • 2015-12-27
    • 2018-09-20
    • 2017-05-28
    • 2017-05-15
    相关资源
    最近更新 更多