5

基本上我们有一个模块,它读取服务器端渲染上的客户端数据,并应该将数据与它找到的数据一起提供给 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>
    );
  }
}
4

1 回答 1

-1

之所以在这里提到它,是因为注释中的所有代码都很难通过上下文传递的值以这种方式访问

<ServerConsumer>{(value) => { console.log(value)}}</ServerConsumer>

您的消费者版本是:

<ServerConsumer>
  {renderChildrenWithServerData(this.props)}
</ServerConsumer>

renderChildrenWithServerData(this.props) 返回一个无状态组件。您需要在下面提到的级别检索上下文数据以将其传递给 renderChildrenWithServerData

<ServerConsumer>
   {(value) => {
     return renderChildrenWithServerData(value, this.props)
   }}
</ServerConsumer>
于 2018-07-23T19:10:41.987 回答