如何在加载数据之前阻止组件呈现?

Non*_*Non 9 javascript reactjs

我正在等待道具从一个名为的商店出来GetDealersStore,而我获取数据的方式是我正在执行的操作:

  componentWillMount () { GetDealersActions.getDealers(); }
Run Code Online (Sandbox Code Playgroud)

我已经测试了应用程序并componentWillMount()在初始渲染之前运行,我有这个

let dealerInfo;
if (this.state.dealerData) {
  dealerInfo = this.state.dealerData.dealersData.map((dealer) => {
    return (<div>CONTENT</div>);
  })
} else {
  dealerInfo = <p>Loading . . .</p>
}
Run Code Online (Sandbox Code Playgroud)

但对于第一第二,你可以看到<p>Loading . . .</p>在这是在屏幕else的上面的条件,再渲染其余想出了return (<div>CONTENT</div>);这是if在有条件的.所以,我想,这意味着render方法已经触发了两次,因为它一直在等待来自数据库的数据.

数据库中的数据在第一次渲染时不可用,因此,如何在第一次初始渲染发生之前获取该数据?

Mat*_*ics 13

您不能使用单个组件执行此操作.您应该遵循容器组件模式以将数据与呈现分开.

let DealersContainer = React.createClass({
  getInitialState() {
    return {dealersData: []};
  },
  componentWillMount() {
    GetDealersActions.getDealers();
  },
  render() {
    let {dealersData} = this.state;
    return (<div>
      {dealersData.map((dealer) => {
        let props = dealer;
        return (<Dealer ...props />); // pass in dealerData as PROPS here
      })}
    </div>);
  }
});
Run Code Online (Sandbox Code Playgroud)

然后更新您的Dealer组件以接收道具并呈现实际内容.


Oli*_*ott 8

我的答案与Mathletics类似,只是更详细.

在这个例子中,我已经将dealerData的状态初始化为null; 这是用于确定容器是否已从商店返回数据的检查.

它是冗长的,但是声明性的,按照你想要的顺序做你想要的,并且它每次都会起作用.

const DealerStore = MyDataPersistenceLibrary.createStore({
  getInitialState() {
    return {
      dealerData: null
    };
  },

  getDealers() {
    // some action that sets the dealerData to an array
  }
});

const DealerInfoContainer = React.createClass({
  componentWillMount() {
    DealerStoreActions.getDealers();
  },

  _renderDealerInfo() {
    return (
      <DealerInfo {...this.state} />
    );
  },

  _renderLoader() {
    return (
      <p>Loading...</p>
    );
  },

  render() {
    const { dealerData } = this.state;

    return (
      dealerData
      ? this._renderDealerInfo()
      : this._renderLoader()
    );
  }
});

const DealerInfo = React.createClass({
  getDefaultProps() {
    return {
      dealerData: []
    };
  },

  _renderDealers() {
    const { dealerData } = this.props;

    return dealerData.map(({ name }, index) => <div key={index}>{name}</div>);
  },

  _renderNoneFound() {
    return (
      <p>No results to show!</p>
    );
  },

  render() {
    const { dealerData } = this.props;

    return (
      dealerData.length 
      ? this._renderDealers()
      : this._renderNoneFound()
    );
  }
});
Run Code Online (Sandbox Code Playgroud)