React Apollo 从状态动态创建查询
React Apollo dynamically create query from state
这是一个典型的情况
我的数据库中有一些字段可以说是颜色、大小、高度...
我可以获取这些字段并将其显示给可以选择这些字段的用户,然后将它们设置为组件状态
我想要实现的是从存储在状态
中的这些字段动态创建 GQL 查询(不是查询变量)
例子
//import react gql ....
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
fields : []
}
}
render(){
...
}
componentWillMount(){
fetch(...)
.then(fields => this.setState({fields}))
}
}
export default graphql( --->state => CREATE_QUERY_DYNAMICALLY_FROM_FIELDS(state.fields)<----,{..some options})
有没有办法在查询创建期间访问组件状态?
或其他一些方法?
任何想法表示赞赏
由于graphql不支持动态查询,尝试使用apollo客户端并有条件地注入查询,甚至你可以使用声明性 <Query .../>
组件。
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
fields : []
}
}
render(){
...
}
componentWillMount(){
const query = gql`
query myDynamicQuery {
viewer {
endpoint {
${this.state.fields.join('\n')}
}
}
}
`
this.props.client.query({ query }).then((res) => ...)
}
}
export default withApollo(MyComponent)
希望这是有效的:)
这是一个典型的情况 我的数据库中有一些字段可以说是颜色、大小、高度...
我可以获取这些字段并将其显示给可以选择这些字段的用户,然后将它们设置为组件状态
我想要实现的是从存储在状态
中的这些字段动态创建 GQL 查询(不是查询变量)例子
//import react gql ....
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
fields : []
}
}
render(){
...
}
componentWillMount(){
fetch(...)
.then(fields => this.setState({fields}))
}
}
export default graphql( --->state => CREATE_QUERY_DYNAMICALLY_FROM_FIELDS(state.fields)<----,{..some options})
有没有办法在查询创建期间访问组件状态?
或其他一些方法?
任何想法表示赞赏
由于graphql不支持动态查询,尝试使用apollo客户端并有条件地注入查询,甚至你可以使用声明性 <Query .../>
组件。
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
fields : []
}
}
render(){
...
}
componentWillMount(){
const query = gql`
query myDynamicQuery {
viewer {
endpoint {
${this.state.fields.join('\n')}
}
}
}
`
this.props.client.query({ query }).then((res) => ...)
}
}
export default withApollo(MyComponent)
希望这是有效的:)