当将GraphQL查询片段作为RelayContainer
的一部分编写时,我一直在努力解决在某些情况下如何设置查询变量的问题。 documentation中概述的基础知识非常简单。但鉴于这些查询的静态特性以及RelayContainer
如何是一个更高阶的React组件,当查询所需的输入是来自外部的对象时,我不确定处理此问题的最佳方法像Redux商店这样的来源。在组件加载之前,我没有办法从该商店检索数据,所以作为一种解决方法,我一直在使用@include
指令并在组件加载后将ready变量设置为true:
class ListData extends React.Component {
// ... proptypes
componentWillMount() {
const { listDataInfo } = this.context.store.getState(); // Retrieve from Redux store
this.props.relay.setVariables({
input: {
id: listDataInfo.id,
user: listDataInfo.user
},
inputReady: true,
});
// The query will now execute and fetch all the data
}
render() {
return (
{/* view */}
)
}
}
export default Relay.createContainer(ListData, {
initialVariables: {
input: null,
inputReady: false,
},
fragments: {
listData: () => Relay.QL`
fragment on ListDataQuery {
listData(input: $input) @include(if: $inputReady) {
city
state
zip
phone
}
}
`,
},
});
最终这会按预期工作,但我担心这更像是一个黑客,而且我错过了Relay应该如何处理查询变量的重要内容。有一个更好的方法吗? prepareVariables看起来很有用,但我仍然无法访问我的数据存储。以下是我明显的选择:
RelayNetworkLayer
(可以访问我的商店)拦截我的查询并从那里的外部商店设置变量。这也感觉就像是黑客。答案 0 :(得分:0)
我发现this gist完全符合我的要求。它允许您通过@container
装饰器使用属性variablesFromState
传递redux状态变量。基本上它将返回一个标准的中继容器(如果未设置variablesFromState
)或一个包含在redux Provider
包装器中的中继容器,并且传入了redux存储实例。