Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

reactjs - GraphQL / Relay - do all tables need to be queried in main QueryRenderer?

I'm new to GraphQL and Relay and I'm struggling with queries, fragments, ...spreads & passing props. I think I'm unnecessarily passing props down through many, many components. I want to learn how to teleport my data objects from the QueryRenderer to deeply nested components, skipping all the ancestor components.

Suppose I have a component structure like this. I need a list of emojis from the 'emoji' table inside EmojisList component which is deep in the app. I'm not sure where to spread or pass props or when to ask for the actual scalars.

<MainApp>
  <QueryRenderer 
    environment={environment}
    query={graphql`
        query MainAppQuery {
        currentPerson { // current user
            ...Timeline_currentPerson
        }
        allEmojis {
            ...ReactionBar_emojisList
          }
        }
    `}
  />
  <Timeline currentPerson={props.currentPerson}>
    <PostList>
      <Post>
        <ReactionBar>
          <EmojisList>
            // I need this list
            export default createFragmentContainer(ReactionBar, {
              emojisList: graphql`
                fragment ReactionBar_emojisList on EmojisConnection @relay(plural: true) {
                  edges {
                    node {
                      name
                      rowId
                    }
                  }
                }
              `,
            });      
          </EmojisList>
        </ReactionBar>
      </Post>
    </PostList>
  </Timeline>
</MainApp>

Console error

question from:https://stackoverflow.com/questions/65868188/graphql-relay-do-all-tables-need-to-be-queried-in-main-queryrenderer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Fragment Container

Wrap <EmojiList /> Component with createFragmentContainer HOC then it will grab all of the data you need that you have fetched at the root from QueryRenderer .

The data will be accessible as props inside the component

// EmojisList.js
import {createFragmentContainer, graphql} from 'react-relay';

class EmojisList extends React.Component {/* code */}

// Export a *new* React component that wraps the original `<EmojisList>`.
export default createFragmentContainer(EmojisList, {
  emojisList: graphql`
    fragment EmojisList_emojisList on EmojisConnection {
      edges {
        node {
         name
         rowId
        }
      }
    }
  `,
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...