
本文介绍了Graphql,react-apollo 如何在加载组件状态时将变量传递给查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的反应组件,必须在用户询问时从服务器加载数据.问题是我不知道如何传输动态变量 SpeakerUrl 并在组件加载状态之前访问它.当然我可以从 this.props.params
访问它,但是组件没有加载,我在进行 graphql 查询时无法访问它.查询 - QuerySpeaker
在我手动设置 url 变量时工作正常.
路由器
组件 - SpeakerPage
从'react'导入React;从'react-apollo'导入{graphql};从'../redux/graphql/querys'导入{QuerySpeaker};class SpeakerPage 扩展了 React.Component {使成为( ) {console.log( this.props );返回 (<div className="ui 容器"><div className="ui grid"><div className="row">你好
)}}导出默认 graphql(QuerySpeaker, {选项:({ url }) =>({ variables: { url } }) <- 这是我的问题,我该如何设置这个 url 变量?})( 演讲者页面 );
解决方案
基于 react-apollo
documentation,传递给options
函数的参数是传递给组件的props对象.当 react-router
渲染你的组件时,它会将 params
作为 prop 传递给它.这意味着 params
应该是传递给 options
函数的对象的属性.
导出默认graphql(QuerySpeaker, {选项:(道具)=>({ 变量: { url: props.match.params.speakerUrl } })})( 演讲者页面 );
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.
Router
<Route path="/speaker/:speakerUrl" component={SpeakerPage} />
Component - 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 如何在加载组件状态时将变量传递给查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!