小编典典

如何防止在加载数据之前渲染组件?

reactjs

我正在等待道具从名为的商店中拿出来GetDealersStore,而我获取数据的方式是通过执行此操作的动作来执行的:

  componentWillMount () { GetDealersActions.getDealers(); }

我已经测试过该应用,并且componentWillMount()在具有此功能的初始渲染之前运行

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

但是对于第一秒,您可以<p>Loading . . .</p>在屏幕上看到else上述条件中的,然后呈现其余的渲染,return (<div>CONTENT</div>);其中是if条件中的。因此,我想这意味着render方法已被触发两次,因为它一直在等待来自数据库的数据。

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


阅读 322

收藏
2020-07-22

共1个答案

小编典典

您不能使用单个组件来执行此操作。您应该遵循容器组件模式将数据与渲染分开。

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>);
  }
});

然后更新您的Dealer组件以接收道具并渲染实际内容。

2020-07-22