2

我在响应中使用上下文 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));
4

1 回答 1

0

导出 HOC 时使用了错误的上下文。

你说:

export default graphql(GetMerchantLocations, { 
    options: (props) => ({
        variables: {
            id: this.props.data.data.id
        },
    })}
)(WithContext(Locations));

在选项中,您可以访问选项范围 props: props.data...

于 2019-07-16T06:55:04.457 回答