中继道具准备变量?

时间:2015-12-13 19:59:29

标签: javascript relayjs

您可以在容器上的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 });
}

然后接力抱怨 提供给location的预期道具LocationList将由Relay进行数据提取。

这可能吗?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

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

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

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