【问题标题】:How to call a graphql query again with different variable value?如何使用不同的变量值再次调用 graphql 查询?
【发布时间】:2018-09-13 01:08:08
【问题描述】:

这是我的代码文件。

import React from 'react'
import { gql } from 'apollo-boost'
import { Query } from 'react-apollo'

const CATEGORY_QUERY = gql`Some query here`

const handleOnCategoryTouch = (id) => {
  //Again call the query
}

const Home = () => (
  <Query
    query={CATEGORY_QUERY}
    variables={{ limit: 20, cursor: "", idcategory: 0 }}
  >
    {({ loading, error, data }) => {
      if (loading) return <Text>Loading...</Text>;
      if (error) return <Text>Error :(</Text>;
      return (
        <Categories
          categories={data.get_discovery_kol_data.categories}
          content={data.get_discovery_kol_data.postKol}
          onCategoryTouch={handleOnCategoryTouch}
        />
      )
    }}
  </Query>

这里的Categories 是一个将类别呈现为UI 中的芯片的组件。点击那个芯片,我们得到 categoryId。现在我想用最新的 id 调用CATEGORY_QUERY 并更新现有结果,怎么做?

我正在使用

"apollo-boost": "^0.1.3",
"graphql": "^0.13.2",
"react": "^16.3.0-alpha.1",
"react-apollo": "^2.1.0-beta.3",
"react-native": "0.54.2",

【问题讨论】:

    标签: react-native apollo


    【解决方案1】:

    最好的方法是创建包装组件

    父.js

    import Home from './Home'
    
    class Parent extends React.Component {
      render() {
        return <Home 
          category={this.state.id} 
          onCategoryChanged={(id) => { this.onCategoryChanged(id) }}
        />
      }
    
      onCategoryChanged (id) {
        this.setState({ id })
      }
    }
    

    Home.js

    class Home extends React.Component {
      render() {
        return (
          <a onClick={() => { this.props.onCategoryChanged(1) }}>Change category to 1</a>
        )
      }
    }
    
    export default graphql(CATEGORY_QUERY, {
      options: ({ category }) => ({
        variables: { category }
      })
    })(Home)
    

    这将强制父组件使用新的 props 重新渲染 Home,并使用 categoryId 的新变量再次调用查询

    【讨论】:

    • 难道不能单独使用react-apollo 中的新Query 组件吗?
    • @Mozak 基本上不管你是从 2.0 开始将 Home 包裹在 HoC 组件中,还是在 render 中使用 Query ,父重新渲染的概念都是一样的。
    • 是的,我使用了您建议的方式,它正在工作。谢谢。
    猜你喜欢
    • 2020-05-17
    • 2013-11-19
    • 2022-01-21
    • 2019-04-11
    • 2022-11-19
    • 2022-08-02
    • 2017-03-14
    • 2017-10-18
    • 2022-11-30
    相关资源
    最近更新 更多