RelayJS:如何通过props设置initialVariables

时间:2015-12-28 11:24:09

标签: reactjs relayjs graphql graphql-js

假设我有一个GraphQL类型Echo,它可以通过一些装饰回显我查询的内容。另一方面,我有一个React组件,回传message传递给它,其中一些装饰由Echo类型决定。如何为initialVariables组件设置Echo

我读到设置道具集initialVariables,但这不起作用。我尝试了componentDidMount,但这也行不通。

Relay Playground表示邮件未正确显示。

对于上下文,

// This component consumes `Echo` type
class Echo extends React.Component {
  componentDidMount() {
    let {relay, message} = this.props; 

    relay.setVariables({
      message
    });
  }

  render() {
    let name = '';
    if (this.props.echo) {
      name = this.props.echo.name;
    }

    return (
      <li>Message: {name}</li>
    );
  }
}

Echo = Relay.createContainer(Echo, {
  // By default `message` is null
  initialVariables: {
    message: null
  },

  fragments: {
    echo: () => Relay.QL`
      fragment on Echo {
        name(message: $message)
      }
    `,
  },
});

这是使用echo

解析的类型
let EchoType = new GraphQLObjectType({
  name: 'Echo',
  fields: () => ({
    name: {
      type: GraphQLString,
      args: {
        message: {
          type: GraphQLString
        }
      },
      resolve: (echo, {message}) => `Hello, ${message}!`
    }
  })
});

1 个答案:

答案 0 :(得分:7)

我承认我对Relay知之甚少,但传递给message的{​​{1}}属性似乎正在影响它(或以其他方式影响它)。我做了以下更改:

  1. 更改传递给Echo的道具名称:

    Echo
  2. 更改<Echo echo={this.props.viewer.echo} defaultMessage="Default"/> 中的媒体资源名称:

    componentDidMount
  3. 以下是完整的来源(和a link to a working example):

    componentDidMount() {
      let {relay, defaultMessage} = this.props; 
    
      relay.setVariables({
        message: defaultMessage
      });
    }