【发布时间】:2018-11-21 02:56:55
【问题描述】:
以下内容适用于通过 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 中运行的脚本 - 等待客户端应用程序手动安装、运行和附加到头部有点太慢了。
更新
这里有一个简单的示例 repo:https://github.com/tills13/nextjs-ssr-context
this.context 在Child 的构造函数中是undefined,如果我将它移动到componentDidMount(目前在repo 中以这种方式设置),它可以工作,但我希望这可以解决服务器-边。我没有死心塌地context,如果有其他方法可以做到这一点,我会全力以赴。
【问题讨论】:
-
你用的是哪个版本的nextjs?这些上下文的 API 是实验性的。 react 16 有新的 API。
-
我正在使用 Next 6.0。 “新”上下文 API (
React.createContext) 在 SSR 中根本不起作用。讨论于github.com/zeit/next.js/issues/4182 / github.com/zeit/next.js/issues/4194 -
尝试将函数调用从构造函数移到componentDidMount
-
@gandharvgarg 没有达到目的,因为
componentDidMount只运行客户端。我需要在服务器端完成此操作。 -
@TarunLalwani 更新
标签: reactjs server-side-rendering nextjs react-context