我试图在反应中使用表单输入来使用graphql和apollo过滤我的mongodb数据库。我已经设置好了后端并且正在工作。我的前端大部分工作正常,除了无法访问阿波罗查询中的数据。不知道我缺少什么,所以不确定要问的确切问题。我只是在做搜索或查询而不是突变。我的React应用程序中有3个组件,并且正在使用样式组件。我只想捕获表单输入数据并将其存储在阿波罗查询中以供使用。我想调用<h1>{data.herb.name}</h1>
并从我的阿波罗服务器获取数据对象。
我知道这是一个完整的问题,因此,如果您不能帮忙,可以给我一些建议,以便更好地以较小的块数进行询问。谢谢。
App.js
import React, { Component } from 'react'
import ApolloClient from 'apollo-boost'
import { ApolloProvider } from 'react-apollo'
import { BrowserRouter as Router, Route, Switch } from 'react-route-dom'
import Home from './components/Home'
import Herb from './components/Herb'
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
})
export default class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/:herbId" component={Herb} />
</Switch>
</Router>
</ApolloProvider>
)
}
}
Home.js
import React, { Component } from 'react'
import styled from 'styled-components'
import SearchInput from './Search'
import Herb from './Herb'
import bgImage from '../Elements/images/measure_colorized.jpg'
const HomeContainer = styled.div`
width: 100vw;
height: 100vh;
background: url(${bgImage});
background-size: cover;
background-repeat: no-repeat;
`
const Title = styled.h1`
font-size: 6rem;
color: #fff;
`
export default class Home extends Component {
state = { name: '' }
handleInput = e => {
const formData = {}
formData[e.target.name] = e.target.value
this.setState({ ...formData })
}
render() {
const { name } = this.state
return (
<HomeContainer>
<header>
<Title>Measure App</Title>
</header>
<SearchInput name={name} onChangeValue={this.handleInput} />
<Herb name={name} />
</HomeContainer>
)
}
}
Search.js
import React, { Component, Fragment } from 'react'
import styled from 'styled-components'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'
const SearchInput = styled.input`
background: rgba(0, 0, 0, 0.6);
width: 30vw;
padding: 1rem;
font-size: 1.6rem;
color: white;
border: none;
`
const SubmitBTN = styled.button`
padding: 1rem;
font-size: 1.6rem;
border: none;
background: #7ff2ca;
`
export default class Search extends Component {
handleSubmit = e => {
e.preventDefault()
}
render() {
const { name, onChangeValue } = this.props
return (
<div>
<Query query={GET_HERB_QUERY} variables={{ name }}>
{(data, loading, error) => {
if (loading) return 'Loading...'
if (error) return `Error: ${error.message}`
console.log(data)
return (
<Fragment>
<SearchInput
name="name"
type="text"
placeholder="search"
value={name}
onChange={onChangeValue}
/>
<SubmitBTN onClick={this.handleSubmit}>convert</SubmitBTN>
</Fragment>
)
}}
</Query>
</div>
)
}
}
//writing query to fetch herb that matches search result
const GET_HERB_QUERY = gql`
query searchHerbs($name: String) {
herb(name: $name) {
name
description
imageURL
}
}
`
答案 0 :(得分:1)
如注释中所述,当用查询包装组件时,将在渲染组件时触发查询。
您可以manually fire the query并根据需要管理数据。您还可以使用refetch方法(使用包装器)使用不同的变量再次触发查询。