【问题标题】:Props in relay prepareVariables?继电器中的道具prepareVariables?
【发布时间】:2016-03-19 06:18:04
【问题描述】:

嗨,我可以访问容器上 prepareVariables 中的道具吗?

我有一个递归结构:

LocationList = Relay.createContainer(LocationList, {
    fragments: {
        location: () => Relay.QL`
            fragment on LocationPart {
                id, children { 
                    id, hasChildren, value,
                    ${LocationListItem.getFragment('location')} 
                }
            }
        `
    }
});
LocationListItem = Relay.createContainer(LocationListItem, {
    initialVariables: {
        expanded: false
    },
    fragments: {
        location: (variables) => Relay.QL`
            fragment on LocationPart {
                id, path, value, description, hasChildren,
                ${LocationList.getFragment('location').if(variables.expanded)}
            }
        `
    }
});

在根上,我将第一级扩展为:

fragment on LocationPart {
    ${LocationListItem.getFragment('location', { expanded: true })}
}

我想保留整个状态并在以后恢复它。 我已经涵盖的保留状态,并且我将带有状态的对象树向下传递给所有节点。 所以我希望能够在 prepareVariables 中做到这一点:

prepareVariables() {
    return { expanded: this.props.open[this.location.id] };
}

我尝试使用构造函数:

constructor(props) {
    super(props);
    if (props.open[props.location.id]) 
        props.relay.setVariables({ expanded: true });
}

但随后中继抱怨 提供给 LocationList 的预期道具 location 将由 Relay 获取数据。

这可能吗?

【问题讨论】:

    标签: javascript relayjs


    【解决方案1】:

    您不能 - prepareVariables 在组件渲染之前运行,并且那里没有可用的道具。而是使用从父级传入的变量。

    【讨论】:

    • 但我如何在上述查询中使用该变量?正如我所说,我尝试使用构造函数,但随后 Relay 抱怨中继未获取数据?
    • 看看以下在 React 生命周期方法中使用 this.props.relay.setVariables API 的要点:gist.github.com/albertstill/…
    【解决方案2】:

    这里的挑战是展开/折叠组件的列表是每个实例的,而中继查询是静态的,并且在创建任何组件之前构建。静态查询每个级别包含一个LocationListItem,而结果将包含一个项目列表。这意味着查询不能代表不同列表项的不同expanded 值,因为查询甚至没有多个列表项。

    这是 GraphQL 和 Relay 中的明确设计决策:查询是静态的,因此大多数查询可以在一次往返中执行(更多解释 on the Relay docs)。在诸如此类的复杂情况下,您可以:

    • 要允许一次获取数据,您可以更改查询本身以接受展开/折叠项目的映射作为输入参数,并相应地调整返回类型。
    • 如果您可以接受一些额外的往返行程,您可以继续使用相同的查询并在 componentDidMount 生命周期方法中使用 setVariables,根据 props 设置扩展变量(就像您在prepareVariables)。

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 1970-01-01
      • 2019-03-12
      • 2020-03-04
      • 2017-02-26
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多