2017-04-03 69 views
1

如果我有這樣的路線:如何將prop從react-router/url傳遞給graphql查詢?

<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

回答

0

要爲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 

你也可以像你在你的例子一樣使用出口撰寫,但我喜歡這樣;)

+0

需要使用的選項箭頭功能,請參見下面https://stackoverflow.com/a/45336215/582309我的回答 – JoshJoe

0

我認爲,你需要使用一個箭頭功能選項

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

const somethingWithData = graphql(somethingQuery, { 
    options (ownProps) => { 
    variables: { 
     id: ownProps.params.id 
    } 
    } 
})(Something) 

export default somethingWithData 

而且,對我來說PARAMS在props.match發現所以它看起來像這樣(在陣營路由器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