简体   繁体   中英

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>

控制台错误

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
        }
      }
    }
  `,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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