正确初始化数据的方法

时间:2015-01-18 17:01:23

标签: javascript reactjs flux refluxjs

使用RefluxJS初始化数据(异步)的正确方法是什么?是否有类似于AngularJS的解决方案,或者Flux实现与此无关(路由器应该处理这种可靠性)?

2 个答案:

答案 0 :(得分:10)

在应用程序的顶级组件中,使用comoponentWillMount方法(docs)来触发提取数据的操作。最初渲染组件时将调用此方法。

例如:

// Create an async action, that will request data using a promise
// Using the recently released (v0.2.2) helpers for async actions
var actions = Reflux.createActions({
    init: {asyncResult: true}
});
actions.init.listenAndPromise(promiseToGetData);

// Update the store when the init action's promise is completed
var store = Reflux.createStore({
    listenables: actions,
    onInitCompleted: function (data) { 
        // do stuff 
        this.trigger(data)
    }
});

var App = React.createClass({
    mixins: [Reflux.connect(store)],
    componentWillMount: function () {
       // When this component is loaded, fetch initial data
       actions.init()
    }
});

答案 1 :(得分:-1)

Reflux实际上有一个API。

文档很难描述它,但Spoike(Reflux'作者)给出了一个答案以及一个代码示例:

https://stackoverflow.com/a/28984512/1775026