【问题标题】:Proper way to initialize data [duplicate]初始化数据的正确方法[重复]
【发布时间】:2015-03-16 17:37:03
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs flux refluxjs


    【解决方案1】:

    在应用程序的顶级组件中,使用 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()
        }
    });
    

    【讨论】:

    • 只是一个问题:如果我使用带有react-router的reflowjs,如果promise被拒绝会发生什么;安装是停止(从技术上讲,没有任何反应)还是手动处理?
    • 组件仍然会挂载,对动作的调用是fire and forget。如果 promise 被拒绝,store 仍然会收到结果,你可以添加一个 onInitFailed 处理程序。有关异步操作的更多信息,请参阅github.com/spoike/refluxjs#asynchronous-actions
    • 谢谢。顺便问一下,你指的是componentWillMount而不是onComponentWillMount
    • 哎呀,对不起,我是componentWillMount,我会修复答案
    • 这段代码 sn-p 至少存在几个问题,这让我有一段时间无法接受。首先,componentWillMount 需要一个函数。另外,actions.load.listen... 应该是actions.init吗?
    【解决方案2】:

    Reflux 实际上有一个 API。

    文档描述得很差,但 Spoike(Reflux 的作者)给出了答案以及代码示例:

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

    【讨论】:

    • 这个问题是关于异步获取数据的。 Reflux 在 React 组件上设置 store 的 getInitialState 方法,不应用于异步获取数据。您链接到的答案中的示例是静态值。示例见官方 React documentationstackoverflow.com/questions/26615307
    猜你喜欢
    • 2017-03-13
    • 2015-03-22
    • 2019-10-24
    • 2019-10-03
    • 2023-03-09
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多