Relay Modern Fragment Container:data props未自动传入问题咨询
data Prop Hey there, let's figure out why your Relay Fragment Container isn't automatically injecting the data prop as expected. I've run into similar snags before, so here are the most common fixes to check off:
1. Double-Check Your Fragment Naming & Container Setup
Relay relies on strict naming conventions to map fragments to component props—this is usually where the issue starts.
Correct Implicit data Prop Setup
If you want data to come through as the data prop without explicit naming, your fragment must match your component's name exactly (no underscore suffix), and you pass the fragment directly to createFragmentContainer (not wrapped in an object):
import { createFragmentContainer, graphql } from 'react-relay'; const ProfileCard = ({ data }) => { return <div>User: {data.name}</div>; }; // Fragment name matches component name: ProfileCard export default createFragmentContainer( ProfileCard, graphql` fragment ProfileCard on User { name email } ` );
If Using Explicit Prop Names (Object Syntax)
If you prefer using an object to define fragments, the key you set will be the prop name. To get a data prop, explicitly use data as the key and follow the ComponentName_propName fragment naming rule:
export default createFragmentContainer( ProfileCard, { data: graphql` // Fragment name follows ProfileCard_data format fragment ProfileCard_data on User { name email } ` } );
2. Ensure Parent Components Include Your Fragment
Relay won't fetch data for your fragment unless it's referenced in a parent query or fragment. If the parent doesn't include your fragment, the data prop will be undefined (making it seem like you have to pass it manually).
Example parent query that includes your fragment:
graphql` query DashboardQuery { viewer { // Reference your component's fragment here ...ProfileCard // Or use the explicit variant: ...ProfileCard_data } } `
3. Verify Your Relay Environment Setup
Your entire app needs to be wrapped in a RelayEnvironmentProvider with a valid environment instance. Without this, Relay can't inject data into your fragment containers at all:
import { RelayEnvironmentProvider } from 'react-relay'; import RelayEnvironment from './RelayEnvironment'; function App() { return ( <RelayEnvironmentProvider environment={RelayEnvironment}> {/* Your component tree goes here */} </RelayEnvironmentProvider> ); }
4. Quick Debug Tip
If you're still stuck, log your component's props to the console. If data is missing entirely, it's almost always one of the above issues—either the fragment isn't linked properly to the component, the parent isn't including the fragment, or the environment isn't set up correctly.
内容的提问来源于stack exchange,提问作者Thomas Grainger

