0

我正在为我的同构应用程序寻找最佳的技术/架构选择。以下是我的限制,由于已经开发的内容,我们需要什么以及我们喜欢什么:

  • React.js中的所有前端,包括布局、子组件等。
  • 通量架构
  • 正如我所说,服务器端渲染(当前服务器是基于 express.js 构建的,它可以更改,但如果我们可以保留它,它将节省一些时间)
  • 非常简单/灵活的路由器,比如 react-router 甚至只是一个 json 路由:组件,我不知道
  • 每个组件都应该能够在渲染之前请求它需要的数据
  • 每个组件都应该能够有一个特定的上下文(设置页面标题、插入特定的 css、设置元标记等)

需要明确的是,我们需要能够在应用程序上添加页面/功能,只需在路由器文件中说“此路由需要在此布局内渲染此组件”,并且该组件应该是独立的,询问“好的,之前一切,我需要这些来自 api 的数据,然后,我需要这个 css 文件,我的标题是'title',等等。”。

我们目前的架构是一团糟,不可维护,不可扩展,不够灵活

使用 Express.js 路由器,我们在每个路由上设置上下文信息,进行 api 调用,然后使用特定的 css 和 js 渲染一个 jam 文件,我们在其中插入 jsx 组件。这是一个例子:

路由器.js

router.get('/profile', function(req, res, next) {
    // make the api call
    api.getProfile(function(err, profile) {
        if (err) {
            next(err);
        }
        // set props for the react component
        var props = {
            profile: profile
        };
        // render the react component
        var ProfileEditor = React.createFactory(
            require('path/to/components/profile.jsx')
        );
        var profileEditor = React.renderToString(
            ProfileEditor(props)
        );
        // render the jade file
        res.render('profile', {
            props: safeStringify(props),
            profile:profileEditor
        });
    });
});

个人资料.jade

// extend a layout
extends ../layout   

// ask for specific styles if need
block styles

// insert the server side rendered component
block component
    #profile 
        != profile

block scripts
    // ask for specific scripts if needed
    script(src="https://maps.googleapis.com/maps/api/js?key=key&libraries=places")
    // print props for the client side rendering
    script(id="props" type="application/json")
        |!{ props }
    // set the react component
    script(src="/bundles/profile.js")

配置文件.jsx

var React = require("react");
var store = require ('../stores/profile');
var actions = require ('../actions/profile');

var Profile = React.createClass({

    // As usual

    render: function(){
        return(
        <div>
                // Profile component
        </div>
        )
    }

});

// re-render client side using the same props from the script tag
if (typeof window !== 'undefined') {
    var ProfileFactory = React.createFactory(Profile);
    var mountNode = document.getElementById("profile");
    var props = JSON.parse(document.getElementById("props").innerHTML);
    React.render(new ProfileFactory(props), mountNode);
}

module.exports = Profile;

随着项目的发展,我们越不满意。

我们一直在尝试探索的解决方案是:

  • yeoman 生成器 react-fullstack:https ://github.com/kriasoft/react-starter-kit/tree/yeoman-generator > 我们发现它非常复杂,我们没有管理如何简单地为每个组件获取数据。尽管这正是我们需要的每个组件的上下文。

  • express.js + react-router:客户端路由(使用react-router)和服务器端路由http ://putaindecode.fr/posts/js/reactjs-et-rendu-serverside/ >同样的数据问题,我们'无法设置上下文。此外,我们对初始渲染服务器端以及所有客户端都不太满意,这与我们目前所拥有的相反。

我们觉得没有什么是真正适应的,而我们没有开发一些真正特别的东西,只是一个从 api 读取/写入数据的平台。

对于我们的约束,什么是最好的、简单的、灵活的、清晰的架构?我们需要做哪些选择?

4

0 回答 0