我是React的新手,正在尝试从API获取数据并构建表格。但现在我想把数据渲染到表格中,我的问题是其中一列是来自URL的标志 index.php?Action=GetLogo&id=51
。结果数量超过300条,即使我已经使用了分页,表格渲染仍然很慢,尤其是logo
列。虽然所有数据都加载完成,但我可以看到每个标志都逐行渲染,给用户带来缓慢的体验。
有没有什么办法让React解决这个问题?请指点我如何解决这个问题。
谢谢大家。
更新
有人建议我使用同步/等待函数来加载图片。然后我更新了代码。然而,我的主要问题仍然存在:加载数据,特别是标志列。虽然所有数据都已呈现,但标志列却没有,然后每个标志开始逐个渲染,看起来非常缓慢。我认为async/await
函数会缓解这个问题。
import React from 'react';
import ReactDOM from 'react-dom';
import FormData from 'form-data';
class FilterableSupplierTable extends React.Component {
constructor(props) {
super(props);
this.state = {
suppliers: []
}
}
componentDidMount() {
let formData = new FormData();
formData.append('AjaxMethodName', 'GetSuppliers');
const options = {
method: 'POST',
headers: {
'Accept': '*/*'
},
body: formData
};
fetch(`?Model=route_to_controller`, options)
.then(response => response.json())
.then(data => {
this.setState({ suppliers: JSON.parse(data.response_data) })
});
}
async getLogos(suppliers) {
return await Promise.all(
suppliers.map(async supplier => {
supplier.new_logo = !!supplier.has_logo ?
<img style={{maxWidth: "100px"}} src={supplier.logo} alt={supplier.supplier_id} /> :
<i className="icon icon-warning no_logo"> No Logo</i>;
return supplier;
});
);
}
render() {
const rows = [];
const suppliers = this.state.suppliers;
this.getLogos(suppliers)
.then(results => {
results.map(supplier => {
rows.push(
<tr>
{/* supplier.logo is index.php?Action=GetLogo&id=51, etc */}
<td><img src={supplier.new_logo} /></td>
<td>{supplier.name}</td>
</tr>
);
});
});
return (
<table>
<thead>
<tr>
<th colSpan="4">Suppliers</th>
</tr>
<tr>
<th>Logo</th>
<th>Name</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
}
ReactDOM.render(
<FilterableSupplierTable />,
document.getElementById('suppliers_list')
);