基本上我们有一个模块,它读取服务器端渲染上的客户端数据,并应该将数据与它找到的数据一起提供给 renderToString (客户端使用 a 渲染window.__SOME_DATA__
,但我不想在快速路由上使用全局)
这是我们的位置:
const contentService = new ServerService();
const app = (
<StaticRouter context={context} location={req.url}>
<App/>
</StaticRouter>
);
try {
await contentService.getSomeData(app);
} catch (error) {
console.log('THERE WAS A MARKUP ERROR', error);
}
const markup = renderToString(
contentService.withProvider(
app
)
);
服务器服务如下所示:
export class ServerService {
items = {};
getSomeData = async (app) => {
// gets some server side data and saves it to the `items` object
};
withProvider = (app) => {
const providedApp = (
<ServerProvider data={this.items}>
{ app }
</ServerProvider>
);
console.log('ITEMS provided', { data: this.items });
return providedApp;
};
getScriptData() {
return `
<script>
window. __SOME_DATA__ = ${JSON.stringify(this.items)};
</script>
`;
}
}
最后但并非最不重要的是我的提供者:
import * as React from 'react';
const ServerContext = React.createContext(null);
export class ServerProvider extends React.Component {
render () {
console.log('Providing data', { props: this.props });
return (
<ServerContext.Provider value={{ ...this.props.data }}>
{this.props.children}
</ServerContext.Provider>
);
}
}
export const ServerConsumer = ServerContext.Consumer;
问题是它似乎可以withProvider
很好地设置函数中的数据,但是当我使用该ServerConsumer
组件时,它似乎什么都不包含——但它应该包含传递给提供者的数据!
当我在客户端需要它时,上下文 api 工作得很好,但在服务器端对我来说似乎失败了。
这是用 react/react-dom16.4.1
评论后更新,这是我使用消费者的方式:
import * as React from 'react';
import { ServerConsumer } from "./serverContext";
import { ContentStateProvider } from "./ContentStateProvider";
const renderChildrenWithServerData = (props) => (state, ...rest) => {
console.log({ state, props, rest }, 'I AM DATA', ServerConsumer);
return (
<ContentStateProvider currentState={state} {...props} />
);
};
export class ContentProvider extends React.Component {
render() {
// console.log({ Consumer }, 'CONTEXT is cool');
return (
<ServerConsumer>{renderChildrenWithServerData(this.props)}</ServerConsumer>
);
}
}