0

我正在尝试将postId变量注入到 fragmentContainer 中。

我已经用with-relay-modern示例开始了这个项目。

变量 $postId 没有正确注入,所以我defaultValue: "UG9zdDoy"同时使用了,但目标是从 props 中获取 postId 的值。

页面 - singlePost.js

import React, { Component } from 'react'
import { graphql } from 'react-relay'
import withData from '_libs/withData'
import PostDetail from '_components/post_page/PostDetail'
import App from '_components/App'

class PostsPage extends Component {
  static displayName = `PostsPage`
  static getInitialProps ({ query }) {
    return { query }
  }

  render (props) {
    const { viewer } = this.props
    return (
          <div>
          {viewer ? <PostDetail {...this.props} 
                        postId={this.props.url.query.postId} 
                        viewer={viewer} 
                        relay={this.props.environment} /> : 'no viewer'}
          </div>
    )
  }
}

export default withData(PostsPage, {
  query: graphql`
    query singlePost_Query { 
      viewer { 
        ...PostDetail_viewer
      } 
    }`,
})

组件 - postDetail.js

import React from 'react'
import PropTypes from 'prop-types'
import { createFragmentContainer, graphql } from 'react-relay'

const PostDetail = (props, {viewer}) => {
  return (
    <div>
      post
    </div>
  )
}

PostDetail.propTypes = {
  viewer: PropTypes.shape({
    post: PropTypes.shape({
      title: PropTypes.string.isRequired,
      description: PropTypes.string.isRequired,
      image: PropTypes.string.isRequired,
      creator: PropTypes.shape({
        firstName: PropTypes.string.isRequired,
        lastName: PropTypes.string.isRequired,
      }).isRequired,
    }),
  }).isRequired,
}

// postId only works with defaultValue, but I need to get it from props.
export default createFragmentContainer(
  PostDetail,
  graphql`
    fragment PostDetail_viewer on Viewer
    @argumentDefinitions(
      postId: {type: "String!", defaultValue: "UG9zdDoy"},
    )
    {
      post (postId: $postId) {
        title
        description
        image
        creator {
          firstName
          lastName
        }
      }
    }
  `,
)

知道如何实现这一目标吗?删除 **defaultValue: "UG9zdDoy" ** 并重新编译会出现以下错误:

RelayCompilerScope:未找到所需参数的值$postId: String!

4

0 回答 0