【问题标题】:How to acess React context from Apollo set Context Http Link如何从 Apollo set Context Http Link 访问 React 上下文
【发布时间】:2020-04-01 13:36:50
【问题描述】:

我正在尝试为我的 Apollo 客户端访问 setContext 函数中的反应上下文值。我希望能够使用反应上下文值动态更新每个 graphql 请求的标头。但是我遇到了一个错误,日志中没有可见的错误消息。我正在尝试做的事情可能吗?

import React, { useState, useContext } from "react";
import { render } from "react-dom";

import ApolloClient from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";

import Select from "./Select";
import CurrencyContext from "./CurrencyContext";
import ExchangeRates from "./ExchangeRates";

const httpLink = createHttpLink({
  uri: "https://48p1r2roz4.sse.codesandbox.io"
});

const authLink = setContext((_, { headers }) => {

  const token = localStorage.getItem("token");


  const currency = useContext(CurrencyContext); // How to access React context here ?


  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
      currencyContext: currency ? currency : {}
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

const currencies = ["USD", "EUR", "BTC"];

const App = () => {
  const [currency, setCurrency] = useState("USD");

  return (
    <ApolloProvider client={client}>
      <CurrencyContext.Provider value={currency}>
        <h2>Provide a Query variable from Context ????</h2>
        <Select value={currency} setValue={setCurrency} options={currencies} />
        <ExchangeRates />
      </CurrencyContext.Provider>
    </ApolloProvider>
  );
};

render(<App />, document.getElementById("root"));

【问题讨论】:

  • 嗨约翰,你有没有进一步了解这个。我正在努力让 setContext 甚至在 Apollo 3 中设置 auth 标头。

标签: reactjs react-hooks react-apollo apollo-client react-context


【解决方案1】:

您可以使用 useImperativeHandle 从 React 树外部访问上下文值 在上下文文件中创建一个 ref

export const ContextRef = React.createRef();

然后在Context里面添加

React.useImperativeHandle(ContextRef, () => contextValues);

最后,您可以使用

访问上下文值
 ContextRef.current.token

见:https://reactjs.org/docs/hooks-reference.html#useimperativehandle

【讨论】:

猜你喜欢
  • 2020-05-20
  • 2021-10-15
  • 1970-01-01
  • 2020-04-02
  • 2020-09-12
  • 2018-09-05
  • 2019-01-10
  • 2020-05-04
  • 2020-07-26
相关资源
最近更新 更多