我正在尝试为我的React应用设置SSR,该应用使用Apollo Client对API进行graphql请求。我已经正确设置了webpack配置和Express应用程序,并且可以看到组件已加载。这里的问题是getDataFromTree
根本没有等待我的查询。它只返回带有loading: true
的组件,然后不返回任何内容。我还设置了ssrForceFetchDelay
,以使客户端重新获取查询,但是什么也没有。
我不断收到window.__APOLLO_STATE__={}
。这些组件非常基础,可以进行简单的查询并显示结果。
这是我的快速应用程序:
app.use((req, res) => {
const client = new ApolloClient({
ssrMode: true,
link: new HttpLink({
uri: 'http://localhost:8000/graphql',
fetch: fetch
}),
cache: new InMemoryCache(),
});
const app = (
<ApolloProvider client={client}>
<Router location={req.url} context={{}}>
<App client={client}/>
</Router>
</ApolloProvider>
);
const jsx = extractor.collectChunks(app); // Using loadable
renderToStringWithData(jsx).then((dataResp) => {
const content = dataResp;
const state = client.extract(); // Always {}
const helmet = Helmet.renderStatic();
const html = ReactDOMServer.renderToStaticMarkup(
<Html content={content} helmet={helmet} assets={assets} state={state} />,
);
res.status(200); res.send(`<!doctype html>${html}`);
res.end();
}).catch(err => {
console.log(`Error thrown`);
});
});
app.listen(port, () => {
console.log(`Server listening on ${port} port`);
});
这是我的客户端Apollo配置:
const cache = new InMemoryCache().restore(window.__APOLLO_STATE__);
const client = new ApolloClient({
ssrForceFetchDelay: 300,
link: links,
cache: cache,
connectToDevTools: true,
});
我的应用程序:
const Wrapped = () => {
console.log(`Inside Wrapped`);
return (
<ApolloProvider client={apolloClient}> //The client one
<Router>
<App /> /*Only returns 2 basic components */
</Router>
</ApolloProvider>
);
};
hydrate(<Wrapped />, document.getElementById('root'));
我可以在页面上看到组件,但是没有加载查询,并且APOLLO_STATE始终为空。我一直在遵循react-apollo
上的文档进行设置,但是我不明白为什么这种基本设置无法正常工作。关于我需要在此处更改的任何想法?谢谢!
HTML组件:
import React from 'react';
const Html = ({ content, helmet, assets, state }) => {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<link rel="manifest" href="/manifest.json" />
<link rel="shortcut icon" href="/favicon.ico" />
{helmet.meta.toComponent()}
{helmet.title.toComponent()}
{assets.css &&
assets.css.map((c, idx) => (
<link key={idx} href={c} rel="stylesheet" />
))}
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root" dangerouslySetInnerHTML={{ __html: content }} />
<script
dangerouslySetInnerHTML={{
__html: `window.__APOLLO_STATE__=${JSON.stringify(state).replace(
/</g,
'\\u003c',
)};`,
}}
/>
{assets.js &&
assets.js.map((j, idx) => (
<script key={idx} src={j} />
))}
</body>
</html>
);
};
export default Html;
编辑:添加了我的HTML组件代码
使用正常工作的基本代码链接到回购。我打算向其中添加Loadable,以查看是否是引起问题的原因。