SSR中的NextJS轨道安装组件

reactjs React.js

小胖Gil

2020-03-23

以下内容适用于通过NextJS进行的SSR。

我正在使用React的上下文来跟踪某些已安装组件的ID。要点是

class Root extends React.Component {
  getChildContext () {
    return {
      registerComponent: this.registerComponent
    }
  }

  registerComponent = (id) => {
    this.setState(({ mountedComponents }) => {
      return { mountedComponents: [...mountedComponents, id ] }
    })
  }

  ...
}

class ChildComponent {
  static contextTypes = { registerComponent: PropTypes.func }

  constructor(props) {
    super(props)

    props.registerComponent(props.id)
  }
}

不幸的是,这仅适用于客户端。this.state.mountedComponents始终[]在服务器上。还有另一种方法可以在服务器端跟踪这些组件吗?基本上,我需要将id提供给脚本才能在head文档中运行-等到客户端应用程序手动安装,运行并追加到头部时,这太慢了。

更新

这是一个快速的示例回购:https : //github.com/tills13/nextjs-ssr-context

this.context is undefined in the constructor of Child, if I move it to componentDidMount (currently set up this way in the repo), it works, but I'd like this to be resolved server-side. I'm not dead-set on context, if there's another way to do this, I'm all ears.

第2688篇《SSR中的NextJS轨道安装组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android