【问题标题】:Access a state value to passing it as parameter of a query访问状态值以将其作为查询的参数传递
【发布时间】:2018-07-10 17:42:56
【问题描述】:

我遇到了一个小问题。作为“react apollo ...”的初学者,我想将状态“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 反应阿波罗版本:2.0.1

【问题讨论】:

  • 似乎是什么问题?没有给出我们无法帮助的错误
  • @Sujit.Warrier 我的问题在于恢复select Carcolor的值。他给我发了这个错误:TypeError:无法读取未定义的属性“selectCarcolor”。似乎 props 无法获取变量const datafetch = graphql(Cquery,{ options: (props)=> ({ variables: { color: this.props.selectCarcolor}, }) }) 我只想将组件状态传递给查询变量

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


【解决方案1】:

您可以使用react-apollo 包中的withApollo 函数包装您的组件,该包将ApolloClient 注入到您的组件中(以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)

【讨论】:

    【解决方案2】:

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

    你能做到吗

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

    而不是你在做什么?

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2016-11-21
      • 2023-01-01
      • 1970-01-01
      相关资源
      最近更新 更多