Flux - 如何使用异步获取的数据初始加载存储数据

Flux - How to initially load Store data with asynchronously fetched data

使用:Vanilla React 和 Flux 火力地堡

我正在努力使我的商店与实时更新同步,所以我一直在按照本文的说明进行操作Handling Synchronized Arrays with Real-Time Firebase Data

我已经调用 WebAPI 实用程序 class 来获取初始数据,并按照说明将其放置在我的顶级组件的 componentWillMount 侦听器中通过 many.The 代码看起来像这样。

var MessageSection = require('./MessageSection.react');
var React = require('react');
var ThreadSection = require('./ThreadSection.react');
var ChatWebAPIUtils = require('../utils/ChatWebAPIUtils');
var ChatApp = React.createClass({

  componentWillMount: function(){
    ChatWebAPIUtils.getAllMessages(); **Here is my call to an action**
  }

  render: function() {
    return (
      <div className="chatapp">
        <ThreadSection />
        <MessageSection />
      </div>
    );
  }

});

module.exports = ChatApp;

问题是即使我的商店将被正确加载,看起来因为它是异步获取,所以会调用渲染组件,其数据仍未准备好。

在我的程序尝试呈现自身之前等待存储初始化的常规方法是什么?

您或许可以为此使用组件状态。

getInitialState() {
    return {
        messagesLoaded: false,
        messages: [],
        threads: []
    }
},
onMessagesLoaded() {
    this.setState({
        messagesLoaded: true,
        messages: ChatWebAPIUtils.messages,
        threads: ChatWebAPIUtils.threads
    });
},
componentDidMount() {
    ChatWebAPIUtils.getAllMessages(this.onMessagesLoaded.bind(this))
},
render() {
    if(!this.state.messagesLoaded) {
        return (<div className="chatapp">Loading...</div>);
    }

    return (
        <div className="chatapp">
            <ThreadSection />
            <MessageSection />
        </div>
    );
}

您将消息和线程的初始状态设置为空数组。 一旦组件挂载,您调用异步函数并向其传递一个回调函数,该回调函数将更新组件的状态——从而导致组件(以及接收新状态的子组件)更新。只要未加载数据 - 就会显示 "Loading" 消息。

也应该可以在 componentWillMount() 部分调用 getMessages 函数。

我想 MessagesSection 应该只显示当前所选线程的消息。我没有在示例中考虑到这一点 - 因此您也必须在某处添加此逻辑。

编辑: 添加了有关防止在加载数据之前呈现子组件的信息。