如何将const变量从一个组件传递到另一个组件

问题描述 投票:0回答:1

你好,我正在尝试将Apollo添加到我的react应用程序中,并在说明中将应用程序包装在<ApolloProvider client={client}>标记中,并将客户端作为变量传递给文档,如下所示:

import React from 'react';
import ReactDOM from 'react-dom';
import PageLayout from './components/page-layout'
import CreateApolloClient from './apollo-settings'
import { ApolloProvider } from '@apollo/react-hooks';
import ApolloClient from 'apollo-boost';
import {BrowserRouter} from 'react-router-dom';

    const client = new ApolloClient({
        uri: 'http://localhost/headless-cms/admin/',
        fetchOptions: {
            mode: 'no-cors',
        },
    });


ReactDOM.render(<ApolloProvider client={client}><BrowserRouter><PageLayout /></BrowserRouter></ApolloProvider>, document.getElementById('site-wrapper'));

但是我想从index.js页面中删除const client并将其移到另一个模板中,只是为了使事情井井有条,就像这样:

import React from 'react';
import { ApolloProvider } from '@apollo/react-hooks';
import ApolloClient from 'apollo-boost';

const CreateApolloClient = () => {
    const client = new ApolloClient({
        uri: 'http://localhost/headless-cms/admin/',
        fetchOptions: {
            mode: 'no-cors',
        },
    });
}

export default CreateApolloClient;

我正在努力的是将CreateApolloClient导入index.js页面时,我如何访问const客户端并将其传递到<ApolloProvider client={client}>

感谢您提供高级帮助

reactjs react-props react-component
1个回答
0
投票

您应该在函数中返回apollo客户端实例并导出createApolloClient

import { ApolloProvider } from '@apollo/react-hooks';
import ApolloClient from 'apollo-boost';

export const createApolloClient = () => {
    return new ApolloClient({
        uri: 'http://localhost/headless-cms/admin/',
        fetchOptions: {
            mode: 'no-cors',
        },
    });
}

export default CreateApolloClient;
import React from 'react';
import ReactDOM from 'react-dom';
import PageLayout from './components/page-layout'
import {createApolloClient} from './apollo-settings'
import {BrowserRouter} from 'react-router-dom';
import { ApolloProvider } from '@apollo/react-hooks';

const client = createApolloClient();

ReactDOM.render(<ApolloProvider client={client}><BrowserRouter><PageLayout /></BrowserRouter></ApolloProvider>, document.getElementById('site-wrapper'));
© www.soinside.com 2019 - 2024. All rights reserved.