Graphql,React-Apollo如何在加载组件状态时将变量传递给查询 [英] Graphql, react-apollo how to transfer variable to query at loading component state
问题描述
我有一个简单的react组件,当用户询问时必须从服务器加载数据.问题是我不知道如何在组件加载状态之前传输动态变量SpeakerUrl并访问它.当然,我可以从 this.props.params
访问它,但是未加载组件,并且在执行graphql查询时无法访问它.查询-当我手动设置url变量时, QuerySpeaker
工作正常.
I have a simple react component that must load data from server when user ask it. Problem is that i don't know how to transfer dynamic variable speakerUrl and access it in before component load state. Sure i can access it from this.props.params
, but component is not loaded and i can't access it when i make a graphql query. Query - QuerySpeaker
is working fine when i manualy set url variable.
路由器
<Route path="/speaker/:speakerUrl" component={SpeakerPage} />
组件-SpeakerPage
import React from 'react';
import { graphql } from 'react-apollo';
import { QuerySpeaker } from '../redux/graphql/querys';
class SpeakerPage extends React.Component {
render( ) {
console.log( this.props );
return (
<div className="ui container">
<div className="ui grid">
<div className="row">
Hello
</div>
</div>
</div>
)
}
}
export default graphql(QuerySpeaker, {
options: ({ url }) => ({ variables: { url } }) <- here is my problem, how can i set this url variable?
})( SpeakerPage );
推荐答案
Based on the react-apollo
documentation, the argument passed to the options
function is the props object passed to the component. When react-router
renders your component, it passes it the params
as a prop. That means that params
should be a property of the object passed to the options
function.
export default graphql(QuerySpeaker, {
options: (props) => ({ variables: { url: props.match.params.speakerUrl } })
})( SpeakerPage );
这篇关于Graphql,React-Apollo如何在加载组件状态时将变量传递给查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!