访问状态值以将其作为查询的参数传递

时间:2018-01-31 14:57:26

标签: reactjs graphql-js react-apollo apollo-client

我有一点问题。作为初学者"反应阿波罗...",我想传递我的州的价值" selectCarcolor"作为我的查询的参数。当我从下拉列表中选择一种颜色时,必须这样做。我在文档中阅读了很多内容,但我不知道从哪里开始。

您可以在此处查看我的所有代码:Github link description here



onChangeCarColor(e){
  //const selectCarcolor = this.state.selectCarcolor
  this.setState({ selectCarcolor:e.target.value})

  console.log("color " + this.state.selectCarcolor);
}

const Cquery = `gql query getAllUsers($color: String!) { 
  getAllUsers(color: $color) {
    _id
    name 
    cars {
      color 
    } 
  } 
}`;
  
const datafetch = graphql(Cquery, {
  options: props=> ({
    variables: { color: **Here I want to pass the select value**},
  })
});




希望得到你的帮助。

谢谢你们!

反应版本:16.2.0 react-apollo版本:2.0.1

2 个答案:

答案 0 :(得分:1)

您可以使用withApollo包中的react-apollo函数来包装您的组件,该ApolloClient包将[{1}}注入您的组件(可用作this.props.client)。您可以使用它发送查询。查看官方docsthis tutorial了解更多详情和解释。

示例:

import React, { Component } from 'react'
import { withApollo } from 'react-apollo'
import gql from 'graphql-tag'
import Link from './Link'

class Search extends Component {

  state = {
    links: [],
    filter: ''
  }

  render() {
    return (
      <div>
        <div>
          Search
          <input
            type='text'
            onChange={(e) => this.setState({ filter: e.target.value })}
          />
          <button
            onClick={() => this._executeSearch()}
          >
            OK
          </button>
        </div>
        {this.state.links.map((link, index) => <Link key={link.id} link={link} index={index}/>)}
      </div>
    )
  }

  _executeSearch = async () => {
    const { filter } = this.state
    const result = await this.props.client.query({
      query: FEED_SEARCH_QUERY,
      variables: { filter },
    })
    const links = result.data.feed.links
    this.setState({ links })
  }
}

const FEED_SEARCH_QUERY = gql`
  query FeedSearchQuery($filter: String!) {
    feed(filter: $filter) {
      links {
        id
        url
        description
        createdAt
        postedBy {
          id
          name
        }
        votes {
          id
          user {
            id
          }
        }
      }
    }
  }
`

export default withApollo(Search)

答案 1 :(得分:0)

在datafetch()函数中,您在props上的函数中设置选项变量,但您将所选颜色设置为您的状态。

你能做到吗

options: {
  variables: { color: this.state.selectCarcolor, }
}

而不是你在做什么?

相关问题