gpt4 book ai didi

javascript - 单独的 ApolloProvider 组件渲染与 ReactDOM 给出错误

转载 作者:行者123 更新时间:2023-12-05 05:38:24 25 4
gpt4 key购买 nike

我在我的 React 应用程序的 index.js 中有以下 ApolloProvider 设置。连接到 Apollo 服务器工作正常。

import { React } from 'react';
import * as ReactDOM from 'react-dom/client';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import App from './App';
import { createHttpLink } from 'apollo-link-http';

const httpLink = createHttpLink({
uri: 'http://localhost:5002'
})

const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
})

export default (
<ApolloProvider client = { client } >
<App/>
</ApolloProvider>
)

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
);

现在我需要解耦它,我尝试在 ApolloProvider.js 中引入一个名为 ApolloProvider 的新组件:

import React from "react";
import App from "./App";
import { createHttpLink } from 'apollo-link-http';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const httpLink = createHttpLink({
uri: 'http://localhost:5002'
})

const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
})

export default (
<ApolloProvider client = { client } >
<App/>
</ApolloProvider>
)

然后我尝试在 index.js 中呈现如下内容:

import ReactDOM from 'react-dom';
import ApolloProvider from './ApolloProvider';

ReactDOM.render(ApolloProvider, document.getElementById('root'));

但是这里我得到了以下错误

ReactDOM.render is no longer supported in React 18. Use createRoot instead.

enter image description here

我用 createRoot 尝试了一些语法仍然没有明确的路径。

最佳答案

在安装 React v18 时,您似乎正在使用用于为 React v17 呈现应用程序的语法。您有两种选择可以使该警告消失:

  1. 更改 index.js 以便您使用 React v18 的设置:
import React from "react";
import ReactDOM from "react-dom/client";
import ApolloProvider from './ApolloProvider';

const root = ReactDOM.createRoot(document.getElementById("root"));
// if you are rendering App as a normal component use this line:
// root.render(<React.StrictMode><App/></React.StrictMode>);
// the below line is specific to how the question is made:
root.render(<React.StrictMode>{ApolloProvider}</React.StrictMode>)

  1. 保持一切不变,但降级您的 React 版本。为此,将下面的三行替换为您在 package.json 中的内容,然后运行 ​​npm inpm start :
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",

关于javascript - 单独的 ApolloProvider 组件渲染与 ReactDOM 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72919077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com