【问题标题】:Relay Playground - how get it to work?中继游乐场 - 如何让它工作?
【发布时间】:2016-10-26 09:59:09
【问题描述】:

我在Relay Playground 中更改了(架构中的“hello”为“text”),如下所示:

架构:

import {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString,
  GraphQLInt
} from 'graphql';

const GREETINGS = 
  {text: 'Hello world 1'}
;

const GreetingsType = new GraphQLObjectType({
  name: 'Greetings',
  fields: () => ({
    text: {type: GraphQLString}
  })
});

export default new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: () => ({
      greetings: {
        type: GreetingsType,
        resolve: () => GREETINGS
      }
    })
  })
});

代码:

class HelloApp extends React.Component {
  render() {
    const {hello} = this.props.greetings;
    return <h1>test: {hello}</h1>;
  }
}

HelloApp = Relay.createContainer(HelloApp, {
  fragments: {
    greetings: () => Relay.QL`
      fragment on Greetings {
        text
      }
    `,
  }
});

class HelloRoute extends Relay.Route {
  static routeName = 'Hello';
  static queries = {
    greetings: (Component) => Relay.QL`
      query GreetingsQuery {
        greetings {
          ${Component.getFragment('greetings')},
        },
      }
    `,
  };
}

ReactDOM.render(
  <Relay.RootContainer Component={HelloApp} route={new HelloRoute()} />,
  mountNode
);

但它不起作用,我没有收到任何错误消息。什么都没有渲染。当我将“文本”改回“你好”时,它再次起作用。为什么?看起来架构是硬编码的?

编辑:

这行得通(我知道为什么):

const sm = this.props.greetings;
return <h1>test: {sm.text}</h1>;

这也有效:

const {text} = this.props.greetings;
return <h1>test: {text}</h1>;

但是下面这个不起作用(我不知道为什么如果上面那个起作用,为什么不能使用自定义变量名?上面的“文本”变量名有什么特别之处?):

const {sm} = this.props.greetings;
return <h1>test: {sm}</h1>;

已解决:

ES6 功能。花括号应该包含属性。这就是text 起作用的原因。谢谢@Vince Ning。

【问题讨论】:

    标签: javascript relayjs


    【解决方案1】:

    在您的 React 应用程序中,您正在像这样解构您的道具:

    const {hello} = this.props.greetings;
    

    由于 greetings 是一个 JSON 对象,因此您只检索了该对象的 hello 属性,而不是它的其余部分。为了获得正确的数据,您可以通过删除该语句中 hello 周围的 {} 来获取整个对象:

    const hello = this.props.greetings;
    console.log(hello.text); // Hello world 1
    

    或者您可以将 {} 中的 hello 更改为文本以检索该特定属性,如下所示:

    const {text} = this.props.greetings;
    console.log(text); // Hello world 1
    

    希望这会有所帮助!

    【讨论】:

    • 谢谢。我让它工作,但我不知道它为什么工作。见编辑。
    • 在 JS ECMAScript 6 中,有一种称为解构 (2ality.com/2015/01/es6-destructuring.html) 的技术,如果您将花括号放在变量周围,它会自动取出在声明中分配的对象的属性。例如,如果你有一个像obj = {first: 1, second 2:} 这样的对象,你可以像const {first, second} = obj; 这样取出属性firstsecond,你可以稍后在你的代码中直接访问firstsecond @ 987654332@ 和second == 2。这有意义吗?
    • 我进行了编辑,那为什么我定义 smvar sm = {text:""} 仍然不起作用?
    • 因为 sm 不是 this.props.greetings 对象的属性
    • 所以有一天我有机会得到这个relay client for existing working graphql server 工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2016-01-26
    • 1970-01-01
    • 2013-04-29
    • 2020-01-05
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多