简体   繁体   English

在服务器端渲染中未定义的React上下文

[英]React Context undefined in Server Side Render

I am trying to pass in data during server side rendering for a simple app. 我正在尝试在服务器端渲染期间为一个简单的应用程序传递数据。

I have this data provider both in the server and client and I use a global variable to inject the initial state into the client: 我在服务器和客户端中都有此数据提供程序,并且使用全局变量将初始状态注入到客户端中:

import React, { Component } from 'react';

export default class SsrDataProvider extends Component {
  constructor(props) {
    super(props);
    this.state = { data: window.__INITIAL_STATE__ };
  }

  getChildContext() {
    return { data: this.state.data };
  }

  render() {
    return this.props.children;
  }
}

SsrDataProvider.propTypes = {
  children: React.PropTypes.object,
};

SsrDataProvider.childContextTypes = {
  data: React.PropTypes.object,
};

In the server, window. 在服务器的窗口中。 INITIAL_STATE gets replaced with the actual data passed in through a prop: INITIAL_STATE被替换为通过prop传递的实际数据:

renderToString(<SsrDataProvider {...renderProps} data={data} />)

and the data provider renders the router context instead of children... 数据提供者呈现路由器上下文而不是子节点...

render() {
  return <RouterContext {...this.props} />;
}

The problem is that the context isn't defined during server rendering. 问题在于服务器渲染期间未定义上下文。 It's like it was never passed in at all. 就像它从未被传递过一样。 Then when the javascript bundle arrives to the client it uses the window. 然后,当javascript捆绑包到达客户端时,它将使用该窗口。 INITIAL_STATE variable and picks up where the server left off. INITIAL_STATE变量,并从服务器停止的地方开始。 It works, but I might as well not do any server side rendering. 它可以工作,但是我也可能不做任何服务器端渲染。 Is there something I'm missing? 有什么我想念的吗? or maybe renderToString() does not support context? 还是renderToString()不支持上下文?

You should be setting the initial state based off of props.data if it is defined. 如果已定义props.data则应设置初始状态。

Really though, you shouldn't even be including window.__INITIAL_STATE__ inside of the component. 确实,您甚至不应该在组件内部包含window.__INITIAL_STATE__ Instead, you should also be passing in the data prop wherever it is that you're rendering the <SsrDataProvider> on the client side. 相反,无论在客户端呈现<SsrDataProvider>任何位置,都应该传递data <SsrDataProvider>

export default class SsrDataProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: props.data // || window.__INITIAL_STATE__
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM