防止构造函数被多次调用React

时间:2017-06-01 03:20:56

标签: reactjs pagination

在我的用例中:我正在进行分页,只有在我的后续分页调用中第一次调用api时才收到数据我只收到分页数据。

如何在React Component中保留以前的数据,因为我再次渲染Component,因此构造函数被调用

我的代码:

    componentWillMount() {
    this.props.dispatch(getSettlementDetails(this.state.settlementParams));
}

componentWillUpdate(nextProps) {
  if(!_.isEmpty(this.props.settlementData) && this.props.settlementData.totalTransactions) {  
   this.settlementData = this.props.settlementData
  }
}

render() {
    let pageDetails = {
        innerPage: true,
        tab: 'Settlements',
        breadCrumbData: [{
            tab: 'Settlements',
            url: 'settlements/'
        }, {
            tab: 'Details',
            url: 'settlements/'+this.props.params.id
        }]
    }

    let downloadProgress;

    /**
    * This is to show or hide download progress
    */
   if(this.props.excelQueue.exportFilterData.showDownloadProgress) {
       downloadProgress = (<DownloadProgress/>)
    }

    if(_.isEmpty(this.settlementData)) {
      this.settlementData = this.props.settlementData
    }

    if (this.props.settlement.fetching) {
        return (
            <div>
                <Header pageDetails={pageDetails}/>
                <div class="main-container">
                    <div>
                       Loading.....
                    </div>
                </div>
            </div>
        )
    } else if(this.props.settlement.fetched){
        return (
            <div>
                <Header pageDetails={pageDetails}/>
                <div class="main-container">
                    <div>
                        <SettlementDetail settlementDataPagination={this.props.settlementData} settlementData={this.settlementData} transactionList={this.props.settlementData.transactionListForSettlementDetailDTOListV1}
                        downloadFile={this.download.bind(this)} dispatchMethod={this.callPaginationApi}/>
                    </div>
                </div>
                {downloadProgress}
            </div>
        )
    } else {
        return (
            <div>
                <Header pageDetails={pageDetails}/>
                <div class="main-container">
                    <div>
                     No Data
                    </div>
                </div>
            </div>
        )
    }



}

现在我将以前的值存储在this.settlementData中,但PaginationComponent会调用其中的constructor

1 个答案:

答案 0 :(得分:0)

可能的解决方案是将状态存储在父组件中。例如。

在父组件声明字段中,保存可以恢复的子项的状态:

controlStates = {};

在您的子组件中,接受对props中父组件的引用(如果您不想在直接父级中存储sttes,则通过context获取)。

然后你可以在构造函数中恢复你的状态:

if (!!props.parent)
{
    this.state = props.parent.controlStates[props.id];
}

并在componentWillUnmount或componentDidUpdate中保存:

if (!!this.props.parent)
{
    this.props.parent.controlStates[this.props.id] = this.state;
}