简体   繁体   English

React Apollo GraphQL,很多查询,但是一个组件可以重用

[英]React Apollo GraphQL, many queries, but one component to be reused

I have this situation: 我有这种情况:

TeamComponent.js: TeamComponent.js:

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

WorkItemComponent.js: 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);

I need to change the query " MY_BEAUTIFUL_WORKTYPE_QUERY " choosing MY_BEAUTIFUL_WORKTYPE_QUERY or MY_VERYBAD_WORKTYPE_QUERY based on " workType " prop in parent component " TeamComponent ". 我需要改变查询“ MY_BEAUTIFUL_WORKTYPE_QUERY ”选择MY_BEAUTIFUL_WORKTYPE_QUERYMY_VERYBAD_WORKTYPE_QUERY基于“ workType ”在父组件“托TeamComponent ”。

But how?! 但是如何?

Maybe I have to rethink everything? 也许我必须重新考虑一切?

Where am I wrong? 我哪里错了?

I think there are two easy approaches you could take here: 我认为您可以在此处采用两种简单的方法:

1) Execute both queries ... and choose which results set you want inside WorkItemComponent. 1)执行两个查询...,然后 WorkItemComponent中选择所需的结果集。 Obviously this is slightly wasteful as you'll be running one query you don't need. 显然,这有点浪费,因为您将运行一个不需要的查询。

2) Export two different components. 2)导出两个不同的组件。 Wrap them in a 3rd component that does the choosing. 将它们包裹在第三个组件中进行选择。 Example code: 示例代码:

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;

So, compose up two different components, and switch between them at render time. 因此,组成两个不同的组件,并在渲染时在它们之间切换。 Functional components and recompose make this rather simple and elegant! 功能组件和重组使其变得相当简单而优雅!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM