将参数从中继路由器传递到组件

Passing parameters from Relay router to component

在中继中,如何将路由参数传递给组件?

我有这条路线:

import Relay from 'react-relay'

export default class ConversationRoute extends Relay.Route {
  static queries = {
    account: (Component) => Relay.QL`
      query root {
        account {
          ${Component.getFragment('account')}
        }
      }
    `
  }

  static paramDefinitions = {
    conversationId: {required: true}
  }

  static routeName = 'ConversationRoute'
}

而这个组件:

class CommentListApp extends React.Component {
  render() {
    let account = this.props.account
    if (!account) return <div />
    return <CommentList comments={account.conversation.comments} />
  }
}

export default Relay.createContainer(CommentListApp, {
  initialVariables: {
    conversationId: null
  },

  fragments: {
    account: () => Relay.QL`
      fragment on Account {
        conversation(id: $conversationId) @include(if: $conversationId) {
          comments {
            ${CommentList.getFragment('comments')}
          }
        }
      }
    `
  }
})

但这不起作用。 conversationId 参数未传递到组件中。

我错过了什么?

您的查询应该是:

static queries = {
  account: (Component, params) => Relay.QL`
    query root {
      account {
        ${Component.getFragment('account', params)},
      },
    }
  `,
}

请注意,在您的案例中,您使用 shorthand 查询语法同样会得到很好的服务。

static queries = {
  account: () => Relay.QL`query { account }`,
}