【问题标题】:How to pass a variable data to createFragementContainer如何将变量数据传递给 createFragementContainer
【发布时间】:2018-04-06 13:45:15
【问题描述】:

我正在使用 Relay Modern 构建我的组件,我想将一个变量传递给片段,以便它可以用作我的查询中的 GraphQL 参数。

这是我正在使用的代码:

class Test extends Component {
    static propTypes = {
       userId: PropTypes.string.isRequired
    }

    render = () => {

        return (

            <p>User Id: {this.props.userId}</p>
            <p>User name: {this.props.viewer.name}
        );
    }
}

export default createFragmentContainer(
    Test,
    graphql`
        fragment Test_viewer on Viewer {
            user(id: $userId) { <<=== The $userId must be the this.props.userId passed
                id
                name
            }
        }
    `
);

当发出查询时,GraphQL 服务器返回错误提示 Variable \"$userId\" is not defined by operation \"UserQuery\"."

我在父组件中的查询:

const UserQuery = graphql` 

  query AdminQuery {
    viewer {
      ...Test_viewer
    }
  }
`

我怎样才能使上面的代码工作?

【问题讨论】:

    标签: javascript reactjs graphql relayjs relay


    【解决方案1】:

    您需要在查询级别传递您的变量:

    const UserQuery = graphql` 
      query AdminQuery($userId: ID!) {
        viewer {
          ...Test_viewer
        }
      }
    `;
    

    &lt;QueryRenderer /&gt; 元素上使用此查询时,您还将将变量作为 prop 传递:

    <QueryRenderer
      query={UserQuery}
      variables={{
        userId: 'USER_ID',
      }}
      // ... others props
    />
    

    【讨论】:

      猜你喜欢
      • 2012-10-31
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2018-04-02
      • 2020-12-20
      • 2011-06-21
      • 2017-10-29
      相关资源
      最近更新 更多