【问题标题】:What is preferred way to pass data dictionaries using relay使用中继传递数据字典的首选方式是什么
【发布时间】:2016-07-19 02:54:52
【问题描述】:

使用中继传递数据字典的首选方式是什么, 例如我在界面中

UsersList = [
   {
     userName 
     // each user has select control
     CountrySelectControl {
         value = Country
         options = [All Countries List]
    }
]

阅读所有国家列表的正确方法是什么? 据我了解,像这样查询 graphQl 不是一个好主意

{ users { userName, country, countriesList } }

所以我看到的唯一方法是我需要在根目录下查询国家列表,并通过 props 手动将其传递给每个子组件?

class Blabla extends Relay.Route {
  static queries = {
    users: (Component) => Relay.QL`
      query UsersQuery {
        users { ${Component.getFragment('user')} },
      }
    `,
    countriesList: (Component) => Relay.QL`
      query countriesListQuery {
        countriesList { ${Component.getFragment('countriesList')} },
      }
    `,
...
}

如果我有很多字典和一些更深的 UI 结构,这会变得很痛苦。

或者我可以以某种方式在树中更深地传递根数据,而无需在 props 中明确写入这些数据。 (我的意思是没有上下文)

【问题讨论】:

    标签: relayjs relay


    【解决方案1】:

    是的,您可以在树中更深地传递根数据,而无需将 countryList 显式写入道具。

    假设,我们有一个大陆及其所属国家的数据。我们有嵌套的 UI 组件。例如,ContinentComponent 包含一个 CountryListComponent,它需要一个国家/地区列表。一个CountryListComponent 由多个CountryComponent 组成,需要一个状态列表。我们可以使用高级道具,而不是让ContinentComponent 传递国家列表和州列表一直到CountryListComponentCountryComponent

    我们可以在高级组件ContinentComponent中指定高级属性continent,如下:

    export default Relay.createContainer(ContinentComponent, {
      fragments: {
        continent: () => Relay.QL`
          fragment on Continent {
            ${CountryListComponent.getFragment('continent')},
          }
        `,
      },
    });
    

    不是country list 属性,而是只有continent 属性从ContinentComponent 传递给CountryListComponent。

    接下来,我们在CountryListComponent中指定必要的props:

    export default Relay.createContainer(CountryListComponent, {
      fragments: {
        continent: () => Relay.QL`
          fragment on Continent {
            countryList(first: 100) {
              edges {
                node {
                  id,
                  name,
                },
                ${CountryComponent.getFragment('country')},
              },
            },
          }
        `,
      },
    });
    

    现在,CountryListComponent 将特定的 prop 值 this.props.continent.countryList.edges[index].node 传递给 CountryComponent。

    这个用例是 Relay.js 的主要动机之一。

    【讨论】:

    • 你仍然需要将这个大陆根 prop 一直传递到你需要的 React 组件。我想明确显示用户使用 CountryList 的主要思想,但如果在 UserList 中使用此列表,我需要在创建时为每个用户传递大量重复项。
    • @ivanstarkov,关于根道具,这是不正确的。例如,CountryComponent 只需要传递 country 属性,如果它不需要根属性下的任何其他内容。关于countryList prop,它不再显式传递给树中的每一层。无论如何,对于您的问题,不同用户的国家/地区列表是否有所不同?
    猜你喜欢
    • 2012-12-20
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 2012-04-02
    • 2021-03-24
    • 2011-03-29
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多