我是做这个 Apollo 的新手。
我目前正在尝试使用 React 和 Apollo 创建一个应用程序。
当我启动我的应用程序时,我收到以下错误:
无法在上下文中找到“客户端”或作为选项传入。将根组件包裹在一个 中,或者通过选项传递一个 ApolloClient 实例。
Here is my RegisterController -> index.tsx
import * as React from "react";
import { ChildMutateProps, graphql } from 'react-apollo';
import gql from 'graphql-tag';
interface Props {
children: (
data: { submit: (values: any) => Promise<null> }
) => JSX.Element | null;
}
class C extends React.PureComponent<ChildMutateProps<Props, any, any>> {
submit = async (values: any) => {
console.log(values);
const response = await this.props.mutate({
variables: values
});
console.log('response: ', response);
return null;
};
render() {
return this.props.children({ submit: this.submit });
}
}
const registerMutation = gql`
mutation($email: String!, $password: String!) {
register(email: $email, password: $password) {
path
message
}
}
`;
export const RegisterController = graphql(registerMutation)(C);
这是我的主要 index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import { ApolloProvider } from 'react-apollo';
import { client } from './apollo';
import { Routes } from './routes';
import "./index.css";
ReactDOM.render(
<ApolloProvider client={client}>
<React.StrictMode>
<Routes />
</React.StrictMode>
</ApolloProvider>,
document.getElementById('root')
);
最后,这是我的 package.json
{
"name": "@abb/controller",
"version": "1.0.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"license": "MIT",
"scripts": {
"build": "rm -rf ./dist && tsc"
},
"dependencies": {
"graphql": "^15.4.0",
"graphql-tag": "^2.11.0",
"react": "^17.0.1",
"react-apollo": "^3.1.5",
"react-dom": "^17.0.1"
},
"devDependencies": {
"@types/node": "^14.14.20",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0",
"typescript": "^4.1.3"
}
}
正如你在我的 index.tsx 中看到的,它被 ApolloProvider 包裹着,客户端从那里传入。 为什么我收到这个错误? 有人可以帮我解决这个问题吗?
谢谢。
答案 0 :(得分:2)
react-apollo
已被弃用。
React Apollo 功能现在可以直接从 @阿波罗/客户
在这里阅读: https://github.com/apollographql/react-apollo#readme
显然,问题在于您的软件包的版本(apollo V3
将一些客户端软件包分组以避免这些问题)。阅读更多:https://www.apollographql.com/docs/react/migrating/apollo-client-3-migration/。
使用 apollo client v3(自 2020 年 6 月起)
改为使用 apollo-client
:https://github.com/apollographql/apollo-client。
命令:
npm install @apollo/client
导入:
import { ApolloProvider } from '@apollo/client'
按照此分步示例进行操作: https://www.apollographql.com/docs/react/get-started/