【问题标题】:passing prop server-side is not being rendered client-side传递道具服务器端未在客户端呈现
【发布时间】:2016-09-02 00:47:44
【问题描述】:

以下 node.js 代码正在渲染我的 App 组件与一个道具...

var reactHtml = reactDom.renderToString(App({exists: true}));
res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml});

这个组件被我的玉文件捕获了......

#app != reactOutput

现在在组件本身中,我正在检查是否渲染了道具...

render(){

        console.log(this.props.exists);
...
...

当我通过终端运行它时,控制台会打印出true。但是,在我的浏览器终端中,我得到了undefined,这意味着 react 是在设置 prop 后在客户端重新渲染组件。

我正在拼命寻找解决此问题的方法,我不想重新构建我的整个网站。有人可以帮我解决这个问题吗?

我是否需要以某种方式阻止重新渲染?

编辑

所以在我的 node.js 文件中我做了以下...

var reactHtml = reactDom.renderToString(App({}));
res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml, errorExist:true});

在我的玉文件中,我做了以下...

#app != reactOutput

script(type='text/javascript')                                                   
    window.data =!{JSON.stringify(errorExist)};

但现在我试图检索组件中的数据...

if (window.data) {
        return (
            <Register />

            );
        }
        else {
            return (
            <Index event={this.handleClick.bind(this)} />

            );
        }  

但我收到错误 windowdata are not defined

【问题讨论】:

  • 您是否仔细检查了客户端在渲染时是否也传递了相同的属性集?在前端重新渲染实际上是完全正常的。您需要的是在客户端和服务器之间为数据建立近乎完美的一对一映射。一种技巧是将数据直接嵌入到 HTML 中的某个地方(可能是一个脚本标签,其中包含以 JSON 编码的数据)。
  • @SalehenRahman 我明白了,你说的直接嵌入数据到底是什么意思,你有例子吗?
  • 在您的 Jade 代码中看起来很像这样:script = JSON.stringify(myData)
  • 然后,在客户端渲染应用程序之前,您将从脚本标签中获取数据,并在渲染时将它们作为属性传递。
  • @SalehenRahman 好的所以我尝试了你的方法,我卡在一个部分,你能看到我的编辑吗?谢谢

标签: javascript node.js reactjs pug


【解决方案1】:

让我们调用{exists: true}初始状态。

1.在服务器端: 使用JSON.stringify 序列化初始状态,并将其存储在翡翠模板中。

node.js

var reactHtml = reactDom.renderToString(App({exists: true}));
res.render('../../tutorHub/views/index.jade', {
  reactOutput: reactHtml, 
  initialState: JSON.stringify({exists: true})
});

玉文件

#app != reactOutput

#initialState =! initialState

2。在客户端: 从 DOM 中获取初始状态,并在 App react 组件的 getInitialState 生命周期方法中使用 JSON.parse 对其进行反序列化

应用反应组件

getInitialState() {
  return JSON.parse(document.getElementById('initialState').innerHTML)
}
  1. exists 布尔值现在可以在 App 组件状态下通过 this.state.exists 访问

【讨论】:

  • 我尝试了你的方法,但我收到document is not defined 错误,这是为什么呢?
  • 请检查getInitialState 以检测document 是否可用。它不会在服务器上呈现。类似if (typeof document === 'undefined') return {};
  • 据我所知,在服务器端渲染中,仍然没有创建浏览器窗口,因此 document 对象不可用,window 也不可用。
猜你喜欢
  • 1970-01-01
  • 2011-12-06
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
相关资源
最近更新 更多