在我的React应用程序中,有一个带有表的页面。表中有三列和一定数量的行(例如,10,即表中的10条记录)。这三列中每一列的数据都是通过对数据库(对数据库中的不同表)进行三次不同的查询而获得的。因此,当将此页面加载到表中时,有时三列中只有一列变满(只完成了其中一个查询),并且在重新加载页面后,表变满。
现在我做了下一步:对于每个对数据库的查询,都有一个带有fetch查询的函数。所有这些函数的调用都在
componentDidMount()如何在从数据库获取所有数据后才能正确呈现页面?
发布于 2019-02-17 20:02:55
目前,您可以这样做:
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}} />
}发布于 2019-02-17 19:59:52
没有代码就不能说太多,但也许可以考虑实现promises/(async/await)来让render等待获取所有数据,然后显示它
发布于 2019-02-17 20:31:23
在完成了获取这3列数据的所有3个调用之后,只需要调用componentDidMount方法。目前,似乎只有一个ajax调用输出就可以调用此方法。
我的建议是,在UI中,您应该只对后端层进行一次调用。在后端代码中,进行3次调用,从3个表中获取数据,并将结果返回给UI。因此,总体来说,从UI到后端只有一次调用,这也会提高性能。
https://stackoverflow.com/questions/54732700
复制相似问题