javascript - 如何将变量数据传递给createFragmentContainer

标签 javascript reactjs graphql relayjs relay

我正在使用 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 服务器返回错误,指出变量\"$userId\"未由操作\"UserQuery\"定义。"

我在父组件中的查询:

const UserQuery = graphql` 

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

如何使上面的代码工作?

最佳答案

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

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

<QueryRenderer /> 上使用此查询时元素,您还将传递变量作为 prop:

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

关于javascript - 如何将变量数据传递给createFragmentContainer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46932923/

相关文章:

javascript - 找不到 CSS 标签

reactjs - 在 ReactJS 应用程序中,如何将全局环境中的 env vars 替换为我的 index.html 文件?

javascript - React Bootstrap 按钮看起来褪色了

graphql - 在页面末尾使用命名导出时,Gatsby 页面查询无法工作。为什么?

javascript - 根据用户输入发送参数

用于从对象范围内访问对象属性的 JavaScript 语法

javascript - 在浏览器的左下方显示可点击的 div 的 URL 预览

javascript - 在 react.js 中,当每个字母都是单独的 <span> (用于动画目的)时,将文本包装在 <p> 标签中

python - Graphite 烯 : Enum argument doesn't seem to work

node.js - NodeJS : How would I compress a stream before uploading to S3?