javascript - ReactJS async rendering
问题描述
I am new with React and cannot write correct code for the situation. Let me explain in the code
class Test extends React.Component {
render() {
// IndexedDB indexes
const ids = ['id1', 'id2', 'id3'];
// fetch data and build a list
const files = ids.map((id) =>
localforage.getItem(id).then((entry) =>
<li key={entry.id}><img src={entry.data} /></li>
);
);
return (
<ul>{files}</ul>
)
}
}
What is the correct way to asynchronous load all data and display it?
解决方案
componentDidMount
您可以在钩子中执行异步逻辑并使用setState
将条目置于您的状态中。
例子
class Test extends React.Component {
state = { entries: [] };
componentDidMount() {
const ids = ["id1", "id2", "id3"];
Promise.all(ids.map(id => localforage.getItem(id))).then(entries => {
this.setState({ entries });
});
}
render() {
return (
<ul>
{this.state.entries.map(entry => (
<li key={entry.id}>
<img src={entry.data} />
</li>
))}
</ul>
);
}
}
推荐阅读
- javascript - 将 pdf 读取为 ArrayBuffer 以将其存储在包含详细信息的 json 文件中
- c# - 找不到类型或命名空间 ExcelDataReader - 但一切编译并运行正常
- python - 如何为 tkinter 标题添加时间倒计时
- amazon-web-services - 为什么我无法从 Lambda 函数访问我的 S3 存储桶?
- c# - C# 将多个值从 TcpClient 发送到远程服务器
- java - 使用 Springboot 读取自己的属性文件
- javascript - 从 IIS 8 运行时,C# .aspx javascript .ajax 自动完成文本框返回 500 错误
- symfony - Symfony Doctrine - 在多对多关系中,为什么补丁在一个方向上工作而不是另一个方向
- angular - 如果条件,防止垫选项选择
- javascript - 来自 Express 订阅调用的 JSON 数组的 Angular HTML 绑定错误