【问题标题】:React ssr(next)-getInitialProps insert a reactNode to props renderReact ssr(next)-getInitialProps 插入一个 reactNode 到 props 渲染
【发布时间】:2020-03-18 00:24:16
【问题描述】:

在 next(react ssr) 中,我尝试像这样渲染页面使用

// this common element, so much project use this, in my private node_modules
const Header = ({ result }) => <div>{result}</div>;

const renderComponent = async () => {
  // mock some request
  const result = await Promise.resolve(10);
  return <Header result={result} />;
};

static getInitialProps = async ctx => {

  return {
    Element: await renderComponent()
  }

}

render({Element}){
  console.log(Element)
  return Element
}
  • 在服务器端,正确的渲染和控制台是
{ '$$typeof': Symbol(react.element),
  type: [Function: Header],
  key: null,
  ref: null,
  props: { result: 10 },
  _owner: null,
  _store: {} }
  • 在 webside dom 渲染一次正确,但很快将错误抛出到空白页面,控制台是

{key: null, ref: null, props: {…}, _owner: null, _store: {…}}
key: null
ref: null
props: {result: 10}
_owner: null
_store: {}
__proto__: Object

那么,如何保持正确渲染公共元素。

【问题讨论】:

  • 我注意到getInitialProps 返回的内容将在第一次加载时在客户端被序列化(JSON.stringify),所以如果它返回{Component:()=&gt;&lt;SomeThing /&gt;},那么它不会有Component。它也会破坏{result:&lt;SomeThing /&gt;}。您可以在页面的渲染函数中返回result 并执行&lt;Header result={this.props.result} /&gt;
  • 是的,如你所说,服务器内存无法共享到网络内存。next将渲染两次。

标签: javascript reactjs next.js


【解决方案1】:

正确的方法就是HMR所说的,在getInitialProps里面获取你的数据,这样会渲染组件两次,需要你自己处理empty/null状态;

static getInitialProps = async ctx => {
  const result = await Promise.resolve(10);
  return {
    result
  }
}

render() {

  // Handle empty state;
  if(!result) return null; // Or <EmptyPage />

  return (
     <Header result={result} />
  )
}

【讨论】:

  • 它将在web端呈现为空页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2020-11-30
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2018-07-01
相关资源
最近更新 更多