Reactjs 访问状态值以将其作为查询的参数传递
我有点小问题。作为“react apollo…”的初学者,我想将状态“selectCarcolor”的值作为查询的参数传递。这必须在我从下拉列表中选择颜色时完成。我阅读了文档中的很多内容,但不知道从何处开始 您可以在此处看到我的所有代码:Reactjs 访问状态值以将其作为查询的参数传递,reactjs,graphql-js,react-apollo,apollo-client,Reactjs,Graphql Js,React Apollo,Apollo Client,我有点小问题。作为“react apollo…”的初学者,我想将状态“selectCarcolor”的值作为查询的参数传递。这必须在我从下拉列表中选择颜色时完成。我阅读了文档中的很多内容,但不知道从何处开始 您可以在此处看到我的所有代码: onChangeCarColor(e){ //const selectCarcolor=this.state.selectCarcolor this.setState({selectCarcolor:e.target.value}) console.log(
onChangeCarColor(e){
//const selectCarcolor=this.state.selectCarcolor
this.setState({selectCarcolor:e.target.value})
console.log(“color”+this.state.selectCarcolor);
}
const Cquery=`gql查询getAllUsers($color:String!){
getAllUsers(颜色:$color){
_身份证
名称
汽车{
颜色
}
}
}`;
const datafetch=graphql(Cquery{
选项:道具=>({
变量:{color:**这里我想传递select值**},
})
});代码>在datafetch()函数中,您正在道具上的函数中设置选项变量,但您正在将所选颜色设置为您的状态
你能做到吗
options: {
variables: { color: this.state.selectCarcolor, }
}
您可以使用react apollo
包中的withApollo
函数来包装组件,该函数将apollo客户机
注入组件(可作为this.props.client
获得)。您可以使用它发送查询。查看官方和官方,了解更多详细信息和解释
例如:
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)
import React,{Component}来自“React”
从'react apollo'导入{withApollo}
从“graphql标记”导入gql
从“./Link”导入链接
类搜索扩展组件{
状态={
链接:[],
筛选器:“”
}
render(){
返回(
搜寻
this.setState({filter:e.target.value})
/>
这是.\u executeSearch()}
>
好啊
{this.state.links.map((link,index)=>)}
)
}
_executeSearch=async()=>{
const{filter}=this.state
const result=等待this.props.client.query({
查询:提要搜索查询,
变量:{filter},
})
const links=result.data.feed.links
this.setState({links})
}
}
const FEED\u SEARCH\u QUERY=gql`
查询FeedSearchQuery($filter:String!){
提要(筛选器:$filter){
链接{
身份证件
网址
描述
创建数据
邮递员{
身份证件
名称
}
投票{
身份证件
使用者{
身份证件
}
}
}
}
}
`
使用Apollo导出默认值(搜索)
出现了什么问题?如果不给出错误,我们就不能help@Sujit.Warrier我的问题在于恢复select Carcolor的值。他向我发送了以下错误:TypeError:无法读取未定义的属性“selectCarcolor”。似乎props无法访问变量constdatafetch=graphql(Cquery,{options:(props)=>({variables:{color:this.props.selectCarcolor},})
我只想将组件状态传递给查询变量