使用同构应用程序设置应用程序初始状态的一般做法是什么?如果没有Flux,我会简单地使用:

var props = { }; // initial state
var html = React.renderToString(MyComponent(props);

然后通过express-handlebars呈现该标记,并通过{{{reactMarkup}}显示.

在客户端设置初始状态时,我会执行以下操作:

if (typeof window !== 'undefined') {
    var props = JSON.parse(document.getElementById('props').innerHTML);
    React.render(MyComponent(props), document.getElementById('reactMarkup'));
}

因此,是的,实际上您在服务器和客户机上设置了两次状态,但是React会比较差异,在大多数情况下,这样不会通过重新渲染影响性能.


当Flux架构中有操作和存储时,这一原则将如何工作?在我的组件中,我可以做到:

getInitialState: function() {
  return AppStore.getAppState();
}

但是现在我如何从服务器设置AppStore中的初始状态呢?如果我在没有传递属性的情况下使用React.renderToString,它将调用AppStore.getAppState(),而AppStore.getAppState()中不会有任何内容,因为我仍然不明白如何在服务器上的存储中设置状态?

更新日期:2015年2月5日

我仍在寻找一个干净的解决方案,不涉及使用第三方Flux实现,比如Fluxible, Fluxxor, Reflux.

更新日期:2016年8月19日

使用Redux.

推荐答案

如果你愿意与alt.js人一起工作,你可以用alt.bootstrapalt.flush(docs)来实现它

我使用带有react服务器端渲染的node js和alt.js作为我的flux实现.

看起来是这样的:

var data = {}; // Get the data whatever you want and return it bootstrap ready.

// Reminder - renderToString is synchronised
var app = React.renderToString(
     AppFactory(data)
);

// In this point the react rendering was finished so we can flush the data and reset the stores

alt.flush();

在我的应用程序中.jsx

/**
 *
 */
componentWillMount: function () {

    // This beauty here is that componentWillMount is run on the server and the client so this is all we need to do. No need for other third-party isomorphic frameworks

    alt.bootstrap(
        JSON.stringify(this.props, null, 3)
    );

}

Reactjs相关问答推荐

如何在没有 node 模块的情况下利用外部Java脚本文件制作OWL carousel

有没有一种方法可以在没有强烈动画的情况下有条件地渲染组件?

React Context未正确更新

GoLang有条件地为.js.gz提供服务(如果它存在),否则为.js

如何使用Reaction Testing Library+Vitest正确更新单元测试中的输入?

在构建或部署Reaction应用程序时出错

如何使我的代码可以接受我想要的每一个链接

useState导致对函数的无休止调用

无法使用导入app/page.jsx的组件中的tailwind 类文本操作和自定义动画

在React中使用if条件时如何更改Tailwind中元素的文本 colored颜色

如何解决使用react-hook-form和yup动态创建的输入不集中的问题

在 React 中将 MUI 样式外包到单独的文件中?

在一个事件处理程序中进行多次调度是个好主意吗?

在 monorepo 内的工作区或库之间共享 redux 状态

将水平滚动视图添加到底部导航选项卡

我正在通过 API(有效)从 MongoDB 传递数据.可视化但我不断收到此 TypeError: Cannot convert undefined or null to object

将 useState 设置为组件内部的值

错误:无效挂钩调用.钩子只能在函数组件的主体内部调用.使用 next/router 时

从输入中获取数字时,react 计数器不会增加

Lodash 在命名导入中导入整个包