繁体   English   中英

下载所有数据后如何呈现页面?

[英]How to render the page after downloading all the data?

在我的React应用程序中,有一个带有表的页面。 表中有三列,并且有一定数量的行(例如,表中有10条记录,即10条记录)。 由于对数据库(对数据库中的不同表)进行了三个不同的查询,因此获得了三列中每列的数据。 结果,当将此页加载到表中时,有时三列中只有一列已满(仅查询之一已完成),并且在重新加载页面后,表已满。

目前,我接下来要做的是:对于数据库的每个查询,都有一个带有访存查询的函数。 所有这些函数的调用都在

componentDidMount()

仅在从数据库获得所有数据后,如何正确呈现页面?

没有代码的话说的不多,但也许可以考虑实现promises /(async / await)来使渲染等待获取所有数据然后显示它

目前,您可以执行以下操作:

class MyTableComponent {
    state = {
        loaded: false
    }

    componentDidMount() {
        Promise.all([this.fetchColumn1(), this.fetchColumn2(), this.fetchColumn3()])
            .then(([column1, column2, column3]) => {
                // Do whatever you want with columns
                this.setState({loaded: true, columns: {column1, column2, column3}})
            });
    }

    render() {
        // render nothing until everything is loaded (You can replace it with loading state
        if(!this.state.loaded) return null;
        else return <Table columns={this.state.columns} />
    }

将来,借助react-cache,可以更整齐地完成相同的工作

const App = (props) => {
    return (
        <Suspense fallback={<p>Loading</p>}
            <MyTable />
        </Suspense>
    )
}

const getColumn1 = () => {...}
const getColumn2 = () => {...}
const getColumn3 = () => {...}
const getColumns = () => Promise.all([getColumn1, getColumn2, getColumn3])
const columnsResource = createResource(getColumns)
const MyTableComponent = (props) => {
    let [column1, column2, column3] = columnsResource.read();

    // Columns will be fetched at this point, unless this line will now execute and nearest parrent suspense fallback will get rendered
    return <Table columns={{column1, column2, column3}} />
}

完成对3列的数据的所有3次调用之后,只有您应该调用componentDidMount方法。 当前,似乎只有一个ajax调用输出就在调用此方法。

我的建议是,从用户界面中,您应该只对后端层进行一次调用。 然后从您的后端代码中进行3次调用,以从3个表中获取数据并将结果返回到UI。 因此,总体上,只有一个从UI到后端的调用,这也将提高性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM