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

时间:2019-12-12 12:36:22

标签: reactjs react-props react-component

您好,我正在尝试将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}>

感谢您提供高级帮助

1 个答案:

答案 0 :(得分:1)

您应该在函数中返回apollo客户端实例并导出 SharedPreferences prefs = await SharedPreferences.getInstance();

 // If the preference firstTime does not exist it means it is the first time
 bool firstTime = prefs.getBool('firstTime') ?? true;

 if(firstTime){

   // This is the first time the user is opening the app

   // Set firstTime preference value to false
   await prefs.setBool('firstTime', false);

 } else{
   // The app has been opened before
 }
createApolloClient