0

我正在将脚浸入节点+猫鼬+反应+回流应用程序中。

我也在尝试创建我的第一个同构应用程序。但是当我浏览整个事情时,我得到以下错误

Running "browserify:client" (browserify) task
>> Error: Cannot find module './mongo' from 'project_folder/node_modules/mongoose/node_modules/mquery/lib/collection'

这个问题发生在我需要('mongoose')某处的那一刻

我认为这是因为猫鼬不能在客户端工作?但我不知道我应该如何填充 (Re)Flux 商店?

这是我正在定义的商店的一个片段(猫鼬已经在另一个文件中连接到 mongo,当我不浏览器时,我确实得到了输出)

var Reflux=require('reflux');
var mongoose=require('mongoose');

var _snippets=[];

var snippetSchema = new mongoose.Schema({
    title: String,
    data: String
});
var Snippet = mongoose.model('Snippet', snippetSchema);

var SnippetStore = Reflux.createStore({

    init: function() {
        Snippet.find(function(err, snippets) {
            _snippets = snippets;
        });
    },


    getSnippets:function() {
        return Snippet.find(function(err, snippets) {
            if (err) return console.error(err);
            return snippets;
        });
    }

});

module.exports=SnippetStore;

4

1 回答 1

0

AFAIK 你不能运行 mongo 客户端。你需要做一些客户端到服务器端的 ajax 东西。

将道具传递给应用程序

同构 JS 的专业提示是使用初始道具启动应用程序(即最顶层的组件),并通过对服务器端的 ajax 调用继续在客户端使用通量/回流/任何内容填充它。

几种方法可以将初始道具推送到您的应用程序。您让服务器呈现道具,例如在脚本标签中(伪代码如下):

// Server-side: Put initial props on the template
<script id="reactprops">
    { JSON.stringify(initialProps) }
</script>

...以及在模板上渲染应用程序:

// Server-side: Render component
React.renderComponentToString(AppComponent(initialProps))

然后客户端应该拿起道具,例如,如果您有一个带有 id 的脚本标签,reactprops您可以使用以下方法获取它们:

// Client-side: Pick up props on #reactprops
var props = JSON.parse(document.getElementById('reactprops').innerHTML);

...然后使用以下命令运行道具:

// Client-side: Render component
React.renderComponent(AppComponent({initialProps: props}));

将道具传递给回流商店

此外,您的应用程序需要启动商店,这很容易componentDidMount在您的应用程序组件中完成。您可以将它收到的初始道具传递给您的回流商店,如下所示:

// You need to create an action that is called when the App has mounted
var Actions = createActions(['appDidStart' /* snip-snip */]);

var App = React.createClass({
    componentDidMount: function() {
        Actions.appDidStart(this.props.initialProps);
    },
    render: function() { /* snip-snip */ }
});

同时,在您的商店中,您需要听取appDidStart行动,如下所示:

var SnippetsStore = Reflux.createStore({
    init: function() {
        this.listenTo(Actions.appDidStart, this.onLoad);
    },
    onLoad: function(initialProps) {
        /* do something with initialProps */
    },
    /* snip-snip */
});

希望这对你有意义。

于 2014-10-27T14:12:08.810 回答