0

我已经阅读了http://scotch.io/tutorials/javascript/build-a-real-time-twitter-stream-with-node-and-react-js,它描述了一种接管服务器渲染的 React 组件的技术无缝地:

服务器渲染到车把中的 {{{markup}}},并传递初始状态。

<section id="react-app">{{{ markup }}}</div>
<script id="initial-state" type="application/json">{{{state}}}</script>

然后在客户端javascript

/** @jsx React.DOM */

var React = require('react');
var TweetsApp = require('./components/TweetsApp.react');

// Snag the initial state that was passed from the server side
var initialState = JSON.parse(document.getElementById('initial-state').innerHTML)

// Render the components, picking up where react left off on the server
React.renderComponent(
  <TweetsApp tweets={initialState}/>,
  document.getElementById('react-app')
);

但是在通量架构中,例如本文http://scotch.io/tutorials/javascript/creating-a-simple-shopping-cart-with-react-js-and-flux中所述,状态在 getInitialState 中初始化生命周期方法:

// Method to retrieve state from Stores
function getCartState() {
  return {
    product: ProductStore.getProduct(),
    selectedProduct: ProductStore.getSelected(),
    cartItems: CartStore.getCartItems(),
    cartCount: CartStore.getCartCount(),
    cartTotal: CartStore.getCartTotal(),
    cartVisible: CartStore.getCartVisible()
  };
}

// Define main Controller View
var FluxCartApp = React.createClass({

  // Get initial state from stores
  getInitialState: function() {
    return getCartState();
  },

  // Add change listeners to stores
  componentDidMount: function() {
    ProductStore.addChangeListener(this._onChange);
    CartStore.addChangeListener(this._onChange);
  },

  // Remove change listers from stores
  componentWillUnmount: function() {
    ProductStore.removeChangeListener(this._onChange);
    CartStore.removeChangeListener(this._onChange);
  },

  // Render our child components, passing state via props
  render: function() {
    return (
      <div className="flux-cart-app">
        <FluxCart products={this.state.cartItems} count={this.state.cartCount} total={this.state.cartTotal} visible={this.state.cartVisible} />
        <FluxProduct product={this.state.product} cartitems={this.state.cartItems} selected={this.state.selectedProduct} />
      </div>
    );
  },

  // Method to setState based upon Store changes
  _onChange: function() {
    this.setState(getCartState());
  }

});

module.exports = FluxCartApp;

从渐进增强的角度来看,哪一种是设置状态的正确方法?

4

1 回答 1

0

考虑到渐进增强,我喜欢通量和反应如何协同工作。

我在当前项目中使用 ReactJS 和 Flux,一切都很干净和简单。您所需要注意的只是在真正需要时展示一些创建新商店的纪律。不过,我不太喜欢 eventEmitter 的东西。我只是触发了我在单独的 eventConstants.js 文件中定义的自己的事件,这使我可以让多个组件在同一个商店中侦听不同的更改。

这确实可以很好地扩展。

回答你的问题:

它确实取决于您的用例。忽略在服务器上呈现初始页面对 SEO 来说非常有用,它只有在用户都应该看到几乎相同的内容时才有意义在服务器上呈现。我喜欢把客户的东西放在客户身上。

我希望这对你有帮助

于 2014-12-17T14:01:28.207 回答