【问题标题】:React Apollo GraphQL, many queries, but one component to be reusedReact Apollo GraphQL,许多查询,但要重用一个组件
【发布时间】:2018-07-09 22:30:51
【问题描述】:

我有这种情况:

团队组件.js:

....more code
  <WorkItemComponent workType="Beautiful">
  <WorkItemComponent workType="VeryBad">
....more code

WorkItemComponent.js:

import React, { Component } from "react";
import { graphql } from "react-apollo";
import { compose, withHandlers } from "recompose";
import MY_BEAUTIFUL_WORKTYPE_QUERY from "./MY_BEAUTIFUL_WORKTYPE_QUERY";
import MY_VERYBAD_WORKTYPE_QUERY from "./MY_VERYBAD_WORKTYPE_QUERY";
import AmazingComponent from "./AmazingComponent";

class WorkItemComponent extends Component {
  <AmazingComponent/>
}

export default compose(
  graphql(MY_BEAUTIFUL_WORKTYPE_QUERY), // <-- here I need to change this query
  choosing from [MY_BEAUTIFUL_WORKTYPE_QUERY, MY_VERYBAD_WORKTYPE_QUERY] based on "workType" prop in parent component "TeamComponent".
  withHandlers({
    ...
  })
)(WorkItemComponent);

我需要更改查询“MY_BEAUTIFUL_WORKTYPE_QUERY”选择MY_BEAUTIFUL_WORKTYPE_QUERYMY_VERYBAD_WORKTYPE_QUERY 基于父组件“TeamComponent”中的“workType”属性。

但是怎么做呢?!

也许我必须重新考虑一切?

我哪里错了?

【问题讨论】:

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


    【解决方案1】:

    我认为您可以在这里采取两种简单的方法:

    1) 执行both 查询...并选择您希望 WorkItemComponent 中的结果集。显然这有点浪费,因为您将运行一个不需要的查询。

    2) 导出两个不同的组件。将它们包装在进行选择的第三个组件中。示例代码:

    const handlers = withHandlers({
      ...
    });
    
    const ComponentOne = compose(
      graphql(MY_BEAUTIFUL_WORKTYPE_QUERY),
      handlers
    )(WorkItemComponent);
    
    const ComponentOne = compose(
      graphql(MY_VERYBAD_WORKTYPE_QUERY),
      handlers      
    )(WorkItemComponent);
    
    const Switcher = ({workType}) => workType === "something" ? <ComponentOne/> : <ComponentTwo/>;
    
    export default Switcher;
    

    因此,组合两个不同的组件,并在渲染时在它们之间切换。函数式组件和重构使这变得相当简单和优雅!

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2021-07-04
      • 2017-07-21
      • 2017-03-25
      • 2017-12-02
      • 2019-10-10
      • 2020-11-04
      • 2020-05-13
      • 2019-09-10
      相关资源
      最近更新 更多