首页 > 解决方案 > 无限获取循环

问题描述

一旦我打开我的 DocumentViewer 获取无限循环,我看不出为什么会发生这种情况,有人可能会看到问题出在哪里,它与状态和道具有关,但我不知道为什么,知道什么会很棒是问题以及如何解决它

class GeneralDocPresenter extends React.Component {

state = {
    metaInfoDocs: [],
    docs: [],
    loading: false
};

updateDoc = () => {
    this.props.selectedDocsStore.clear();
    this.props.selectedDocsStore.setViewDocId(0);
    this.setState({ loading: true });
    this.props
        .fetchMetaDocs()
        .then((r) => this.setState({ metaInfoDocs: r.data, loading: false }))
        .catch((err) => {
            this.setState({ loading: false });
            errorWithMessage("Could not load documents");
        });
    this.props.eventManager.on("viewDoc", (doc) => {
        this.loadDocuments(doc.id);
    });
};

componentDidUpdate(prevProps, prevState, snapshot) {
    this.updateDoc()
}

componentDidMount() {
    this.updateDoc()
}

render() {

    return <Translation>
        {(t) => {
            if (this.state.loading) {
                return (
                    <div style={{display: 'flex', justifyContent: 'center'}}>
                        <Spin size={"medium"}/>
                    </div>
                )
            }
            if (this.state.metaInfoDocs.length === 0) {
                return (
                    <div style={{display: 'flex', justifyContent: 'center'}}>
                        <NoDocumentsAlert><div dangerouslySetInnerHTML={{__html: t('noDocuments')}}/></NoDocumentsAlert>
                    </div>
                )
            }
            return (
                <DocViewWrapper docs={this.state.docs}
                                metaInfoDocs={this.state.metaInfoDocs.map(doc => {
                                    return {...doc, type: this.props.type}
                                })}
                                eventManager={this.props.eventManager}
                                settings={this.props.settings}
                                childComponents={this.props.childComponents}
                />
            )
        }}
    </Translation>
}

loadDocuments(id) {
    this.props.loadDocument(id).then(r => {
        this.setState({
            docs: r.data
        })
    });
}

}

标签: javascriptreactjs

解决方案


尝试ComponentDidUpdate

componentDidUpdate(prevProps, prevState, snapshot) {
    this.updateDoc()
}

componentDidUpdate(prevProps, prevState, snapshot) {
   if(this.props !== prevProps){
    this.updateDoc()
   }
}

您可以更具体地指定 didUpdate 要检查的内容,而不是检查完整的道具更改。


推荐阅读