服务器上具有react.js的交互式Web应用程序

时间:2018-12-18 16:08:21

标签: javascript ruby reactjs web-frameworks

我正在寻找用于交互式实时Web应用程序的Web框架,而无需编写客户端(浏览器),一切将由服务器完成

在Phoenix(Elixir / Erlang)中有一个这样的框架-LiveView,请参见下面的演示。 我正在寻找JavaScript / TypeScript或Ruby中的类似内容

它是如何工作的,最好通过示例进行演示。让我们想象一下,我们已经在JavaScript中建立了这样的框架并构建了一个自动完成组件。看起来几乎像React.JS,但有很大的不同-它将在服务器上运行:

class Autocomplete extends MagicServerSideReactComponent {
  state = { 
    query:       '',
    suggestions: []
  }

  async search(e) {
    const query = e.target.value

    // This whole component runs on the Server, not in the Browser.
    // So it has full access to the Server infrastructure and Database.
    const suggestions = await db.find(`select like '${query}'`)

    this.setState({ query, suggestions })
  }

  render() {
    return <div>
      <input value={this.state.query} onKeyPress={this.search}/>
      {this.state.suggestions.map((name) => <div>{name}</div>)}
    </div>
  }
}

工作原理:

When rendered first time:

- Autocomplete component get rendered on the Server and final HTML sent 
  to the Browser. 
  The Server remembers the `state` and the Virtual DOM - i.e. it's a 
  statefull Server, not usual Stateless node.js Server.
- Browser gets the HTML and renders it into DOM.

When user type something in the input: 

- Browser serializes the Event and sends it to the Server, 
  something like  `{ method: 'Autocomplete.search', event: '...' }`
- Server get the serialized Event and the previously stored Virtual DOM 
  for the given Web Page.
  Then Server process the Event, and as a result the Virtual DOM 
  on the Server gets updated.
  Then Server finds out the difference between the new and old Virtual DOM 
  and generates the DIFF.
  Then Server sends the DOM DIFF to the Browser
- Browser gets the DOM DIFF and modify its DOM.
  And the user see its Web Page updated with the search suggestions.

您知道JavaScript或Ruby中的任何此类网络框架吗?

请不要建议这样做的框架-但是您必须手动更改DOM。 服务器上的虚拟DOM很重要,因为它可以自动更新DOM。它不一定与React.JS完全一样,但它应该像React一样自动更新DOM。

P.S。

  • 为什么?由于分布式系统的第一定律-“不要构建分布式系统”。 更简单是将Web应用程序构建为一个应用程序,而不是将其分发到客户端和服务器中。
  • 延迟-是的,没有什么是免费的,您必须为此付出代价,而延迟将是代价。互动将被延迟-往返于服务器。
  • 性能-是的,服务器不再是无状态的,它是有状态的,运行虚拟DOM并消耗更多资源。

1 个答案:

答案 0 :(得分:0)

您可以通过ebay(https://markojs.com/docs/server-side-rendering/)看一下marko,但我认为您找不到符合所有要求的框架/库。

  

由于分布式系统的第一定律-“不要构建分布式系统”。将Web应用程序构建为一个应用程序比将其分发到客户端和服务器中更为简单。

您使用react或任何其他单页应用程序框架发送给用户的代码正在定义视图。因此,您不应将其视为系统。只是html,css,js和用户数据

  

服务器上的虚拟DOM很重要,因为它允许更新DOM   自动。

为什么目标是更新DOM? DOM只是您的状态/数据的视图。而且您的前端应用程序只是从状态到DOM的映射器/哈希函数。因此,如果您只在服务器中拥有状态,那么您也将拥有DOM。

如果您不想同时编写服务器和客户端,但仍然希望拥有带有数千个开源存储库的精美前端功能,则可以尝试react + firebase。