【发布时间】:2016-04-08 00:09:43
【问题描述】:
Relay 定义了 graphql 片段。我有一个将当前用户的 ID 作为参数。
当前用户 ID 存储在我的 redux 存储中。
如果我想设置用户 ID 中继变量,我可以在组件的生命周期方法之一中进行。然而,relay 期望在initialVariables 中声明一个值。由于这是在模块加载时评估的,因此它无法访问 redux 存储。
作为一种解决方法,我已将 'NULL' 硬编码为中继的 initialVariables 字典中的 userId 变量。但是,这会导致中继发出一个初始请求,将其作为用户 ID 传递,然后在生命周期方法运行后发出另一个请求 - 调用 setVariables - 将用户 ID 更新为来自商店的真实用户 ID。这也会导致组件在第二次调用完成之前呈现不完整的数据。
有没有更好的方法让relay和redux一起玩,这样我就可以从redux中的值设置relay变量?我不希望它为了性能而进行 2 次网络调用,也因为我不希望组件呈现不完整的数据。
我要解释的示例代码是:
class App extends React.Component {
componentWillMount() {
const relay = this.props.relay;
relay.setVariables({ userId: this.props.userStore.id});
}
...
}
export default Relay.createContainer(connect(fullStoreSelector)(App), {
initialVariables: {
userId: 'NULL' // we need to pass a dud string here that
// returns empty data because we have to
// set relay variables in componentDidMount
},
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
user(id: $userId) {
id
firstName
}
}
`
}
});
【问题讨论】: