【问题标题】:Could not find "client" in the context or props of Mutation在 Mutation 的上下文或道具中找不到“客户”
【发布时间】:2020-12-19 06:03:30
【问题描述】:

执行我的 React Native 应用程序后,我遇到了这个错误: Could not find "client" in the context or props of Mutation. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance via props.

这是我的阿波罗客户

import { Platform } from "react-native";
import { ApolloClient, InMemoryCache } from "@apollo/client";

// To access our host machine and not the device itself we use a special ip on android
// If we are using IOS access localhost:4000 else use 10.0.0.2:4000
const host =
  Platform.OS === "ios" ? "http://localhost:4000" : "http://10.0.2.2:4000";

export const client = new ApolloClient({
  uri: host,
  cache: new InMemoryCache(),
});

这里是包装我的根组件的 index.tsx:

import { ApolloProvider } from '@apollo/client';
import { client } from "./apollo";
import { Routes } from "./routes/index";

export default class App extends React.PureComponent {
  render() {
    return (
      <ApolloProvider client={client}>
        <Routes />
      </ApolloProvider>
    );
  }
}

【问题讨论】:

    标签: reactjs react-native apollo-client


    【解决方案1】:

    在 V 3.0 之前,react-apolloapollo-client(以及其他子包)位于单独的包中(产生了很多与包版本相关的问题/错误。Issue 2042 -或- issue 2900)。

    最好的办法是迁移到 Apollo Client 3.0

    react-apollo 包已弃用,功能 上述每个包提供的现在可以从 @阿波罗/客户。 Migrating to Apollo Client 3.0

    Apollo V3.0 很棒的“入门”/教程示例 + 沙盒:

    客户

    在您的情况下,client 似乎是未定义的。运行和测试:

    console.log(client); /* return object -or- not? */
    

    尝试在一个文件中运行此代码(如果此代码工作正常 - 将您想要的文件分开并使用module.exports)。

    import React from "react";
    import { render } from "react-dom";
    import {
    ApolloClient,
    InMemoryCache,
    ApolloProvider,
    useQuery,
    gql
    } from "@apollo/client";
    
    
    export const client = new ApolloClient({
      uri: "https://48p1r2roz4.sse.codesandbox.io",
      cache: new InMemoryCache()
    });
    
    
    export default class App extends React.PureComponent {
    render() {
      return (
        <ApolloProvider client={client}>
            <h2>My first Apollo app <span>?</span></h2>
        </ApolloProvider>
      );
    }
    }
    
    render(<App/>, document.getElementById("root"));
    

    【讨论】:

    • 我已经更新了代码以使用@apollo/client,但我仍然遇到同样的错误。 Routes 会不会和它有关?
    • 很遗憾我没能做到。
    猜你喜欢
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2018-10-08
    • 2018-04-30
    • 2018-08-02
    • 2017-06-13
    相关资源
    最近更新 更多