如何将值从 Redux 传递给 AppolloBoost 客户端?

How to pass value to AppolloBoost client from Redux?

我想将存储在 redux 中的令牌传递给 Apollo Boost 客户端。你如何使用 redux-react-hook 库实现这一点?

import ApolloBoost from 'apollo-boost'

const client = new ApolloBoost({
  uri: 'https://api.github.com/graphql',
  request: (operation) =>{
    operation.setContext({
      headers:{
        Authorization: `bearer ${token}`
      }
    })
  }
});

export default client

编辑:尝试了以下但失败了

import {useCallback} from 'react'
import ApolloBoost from 'apollo-boost'
import {useMappedState} from 'redux-react-hook'

const client = new ApolloBoost({
  uri: 'https://api.github.com/graphql',
  request: (operation) =>{
    const mapState = useCallback(state => state.token, [])
    const token = useMappedState(mapState)   
    console.log(token)
    operation.setContext({
      headers:{
        Authorization: `bearer ${token} ` 
      }
    })
  }
});

export default client

下面是诀窍。我没有为客户端提供单独的文件,而是将代码集成到 App.js 中,然后我能够通过 redux 传递令牌。

import React, {useCallback} from 'react'
import {ApolloProvider} from "react-apollo"
import ApolloBoost from 'apollo-boost'
import {BrowserRouter, Route, Switch, Link} from 'react-router-dom'
import {useMappedState} from 'redux-react-hook'

import SampleComponent from './components/SampleComponent'
import StarredRepos from './components/StarredRepos'
import TokenSession from './components/TokenSession'

export default function App(){

  const mapState = useCallback(state => state.token, [])
  const token = useMappedState(mapState)   

  const client = new ApolloBoost({
    uri: 'https://api.github.com/graphql',
    request: (operation) =>{
      console.log(token)
      operation.setContext({
        headers:{
          Authorization: `bearer ${token} ` 
        }
      })
    }
  });

    return (
      <ApolloProvider client={client}>
        <BrowserRouter>
          <div className="App">
            <div><Link to = {'/SampleComponent'}>SampleComponent</Link></div>
            <div><Link to = {'/StarredRepos'}>StarredRepos</Link></div>
            <div><Link to = {'/TokenSession'}>TokenSession</Link></div>
            <Switch>
              <Route path='/sampleComponent' component={SampleComponent}/>
              <Route path='/StarredRepos' component={StarredRepos}/>
              <Route path='/TokenSession' component={TokenSession}/>
            </Switch>
          </div>
        </BrowserRouter>
      </ApolloProvider>
    );
}