gpt4 book ai didi

ruby-on-rails - 使用 Rails + React-rails gem + React Router 进行服务器渲染

转载 作者:行者123 更新时间:2023-12-03 13:46:28 33 4
gpt4 key购买 nike

我创建了这个示例存储库,它使用rails(v4.2.6)与react-rails(v1.6.2)和react-router(v2.0.0-rc5):https://github.com/pioz/rails_with_react_and_react_router_example

在文件 app/views/application/react_entry_point.html.erb 中,我使用 MountUp 渲染组件

<%= react_component('MountUp', {}, {prerender: false}) %>

组件MountUp渲染我的路由器:

class MountUp extends React.Component {
render() {
return(
<Router history={History}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/contact" component={Contact}/>
<Route path="/about" component={About}/>
</Route>
</Router>
)
}
}

一切正常,但如果我更改选项 prerender: true 我会收到一个奇怪的错误 React::ServerRendering::PrerenderError in Application#react_entry_point:

Encountered error "Error: Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings." when prerendering MountUp with {}
Object.invariant [as default] ((execjs):21983:16)
createHashHistory ((execjs):24108:130)
(execjs):22633:20
wrapDeprecatedHistory ((execjs):25285:61)
createRouterObjects ((execjs):25259:23)
componentWillMount ((execjs):25228:38)
ReactCompositeComponentMixin.mountComponent ((execjs):8138:13)
wrapper [as mountComponent] ((execjs):3131:22)
Object.ReactReconciler.mountComponent ((execjs):6583:36)
ReactCompositeComponentMixin.mountComponent ((execjs):8153:35)
/Users/pioz/.rvm/gems/ruby-2.3.0/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:39:in `exec'
...

如何在服务器端渲染此应用程序?这是正确的方法吗?

最佳答案

找到了解决方案:我们需要两个版本的组件MountUp:一个使用浏览器历史记录的客户端版本和一个使用假内存历史记录的服务器版本。这是该组件的两个版本:

// client version
class MountUp extends React.Component {
render() {
return(
<Router history={History}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/contact" component={Contact}/>
<Route path="/about" component={About}/>
</Route>
</Router>
)
}
}


// server version
class MountUp extends React.Component {
render() {
return(
<Router history={createMemoryHistory(this.props.path)}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/contact" component={Contact}/>
<Route path="/about" component={About}/>
</Route>
</Router>
)
}
}

我们还需要使用等于请求的 url 路径创建内存历史记录:为此,我们可以将一个新的 prop path 与请求的路径传递给组件:

<%= react_component('MountUp', {path: request.path}, {prerender: true}) %>

关于ruby-on-rails - 使用 Rails + React-rails gem + React Router 进行服务器渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35939324/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com