5

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

我读到设置 props sets 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)
      }
    `,
  },
});

这是用回声解决的类型

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

1 回答 1

8

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

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

    <Echo echo={this.props.viewer.echo} defaultMessage="Default"/>
    
  2. 更改属性名称componentDidMount

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

这是完整的源代码(以及一个工作示例的链接):

class Echo extends React.Component {
  componentDidMount() {
    let {relay, defaultMessage} = this.props; 

    relay.setVariables({
      message: defaultMessage
    });
  }

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

    return (
      <li>Message: {name}</li>
    );
  }
}
Echo = Relay.createContainer(Echo, {
  initialVariables: {
    message: ""
  },
  fragments: {
    echo: () => Relay.QL`
      fragment on Echo {
        name(message: $message)
      }
    `,
  },
});

class EchoApp extends React.Component {
  render() {
    return <ul>
      <Echo echo={this.props.viewer.echo} defaultMessage="Default"/>
    </ul>;
  }
}
EchoApp = Relay.createContainer(EchoApp, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        echo { ${Echo.getFragment('echo')} },
      }
    `,
  },
});

class EchoRoute extends Relay.Route {
  static routeName = 'Home';
  static queries = {
    viewer: (Component) => Relay.QL`
      query {
        viewer { ${Component.getFragment('viewer')} },
      }
    `,
  };
}

ReactDOM.render(
  <Relay.RootContainer
    Component={EchoApp}
    route={new EchoRoute()}
  />,
  mountNode
);
于 2016-01-09T09:35:17.590 回答