我在响应中使用上下文 api 将数据传递给子组件。我遇到的问题是我需要使用从上下文传递的数据作为变量来运行 graphql 查询。我创建了一个 HOC 并成功地能够从渲染函数内的 props 访问数据,但我无法访问 graphql 查询中的值。
上下文.js
import React, { Component } from 'react';
export const Context = React.createContext();
export const { Consumer, Provider } = Context;
export const WithContext = (Component) => {
return (props) => (
<Consumer>
{value => <Component {...props} data={value} />}
</Consumer>
)
}
组件.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { GetMerchantLocations, GetMerchant } from '../../data/queries';
import { Consumer, WithContext } from './context';
class Locations extends Component {
render(){
console.log(this.props.data.data);
return (
<div className="locations-container">
<div className="flex grid-header vertical-center">
<div className="item">
<h3>Manage Locations</h3>
</div>
<div className="item">
<div className="btn">Create Location</div>
</div>
</div>
<div className="table-row table-header grid" style={rowStyle}>
<div>Location</div>
<div>Manager</div>
<div></div>
<div></div>
</div>
<div className="table-body">
</div>
</div>
);
}
}
export default graphql(GetMerchantLocations, {
options: (props) => ({
variables: {
id: this.props.data.data.id
},
})}
)(WithContext(Locations));