【发布时间】:2015-03-16 17:37:03
【问题描述】:
使用 RefluxJS(异步)初始化数据的正确方法是什么?是否有类似于 AngularJS 的解析,或者 Flux 实现与此无关(路由器应该处理此责任)?
【问题讨论】:
标签: javascript reactjs flux refluxjs
使用 RefluxJS(异步)初始化数据的正确方法是什么?是否有类似于 AngularJS 的解析,或者 Flux 实现与此无关(路由器应该处理此责任)?
【问题讨论】:
标签: javascript reactjs flux refluxjs
在应用程序的顶级组件中,使用 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()
}
});
【讨论】:
onInitFailed 处理程序。有关异步操作的更多信息,请参阅github.com/spoike/refluxjs#asynchronous-actions。
componentWillMount而不是onComponentWillMount?
componentWillMount,我会修复答案
componentWillMount 需要一个函数。另外,actions.load.listen... 应该是actions.init吗?
Reflux 实际上有一个 API。
文档描述得很差,但 Spoike(Reflux 的作者)给出了答案以及代码示例:
【讨论】:
getInitialState 方法,不应用于异步获取数据。您链接到的答案中的示例是静态值。示例见官方 React documentation 和 stackoverflow.com/questions/26615307