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

How can I prevent a component from rendering before data is loaded?

本文关键字:数据 加载 何防止 组件      更新时间:2023-09-26

我正在等待道具从名为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在条件。我猜,这意味着渲染方法被触发了两次因为它一直在等待来自数据库的数据。

来自数据库的数据在第一次渲染时不可用,所以,我如何在第一次初始渲染发生之前获取该数据?

您不能对单个组件这样做。您应该遵循容器组件模式,将数据与呈现分离。

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组件来接收道具并呈现实际内容。

我的答案与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()
    );
  }
});