reactjs - componentDidMount() 中的同步操作
问题描述
我有一个有状态的组件,我在其中获取一个用户列表componentDidMount()
。在我检查列表是否为空之后,如果是,则创建一个占位符来显示。
由于列表的获取是一个异步操作,我可能不应该像这样检查空列表:
componentDidMount() {
this.props.dispatch(fetchUsersOfList());
if (this.props.userBases.length === 0) {
...
}
}
我目前通过在 a 中编写 if 语句来解决这个问题componentDidUpdate()
:
componentDidUpdate(prevProps) {
if (this.props.userBases.length === 0) {
if (this.props.currentBase !== prevProps.currentBase) {
...
}
}
}
我正在使用 redux 并在每个函数运行/完成后更新状态。现在的问题是,每次我延迟这样的操作时,我都会延迟向用户显示数据。最终,这加起来并且很明显。因此,用户看到转动加载轮的时间增加了。
有没有另一种更快的方法来解决这个概念?
解决方案
我相信您正在从您的操作中返回响应有效负载并抛出错误。你得到你解决的承诺是then
这样的:
componentDidMount() {
this.props.dispatch(fetchUsersOfList()).then((response)=>{
if (// your condition goes here") {
...
}
})
}
随时问任何问题
推荐阅读
- rpa - 如何在搜索框中输入我的击键?
- kotlin - 从多个 Kotlin Coroutines 挂起函数到单个同步函数
- mysql - 仅为 MySQL 中的返回查询设置自定义时区
- javascript - 更好/更快的方法来提取具有条件的嵌套对象上不同深度的匹配属性的值
- python - 为什么使用 strptime 时会出现此 datetime 日期错误
- python-3.x - 如何迭代 Tensorflow 中的张量并在必要时更改其值?
- c - 在 BLE 中通过 GATT 发送/接收字符串
- node.js - 让 node.js 在 unbuntu 14.4 上启动时运行
- node.js - 在 Digitalocean 上运行的 Vue 应用程序在浏览器中超时
- reactjs - 如何修复错误:尝试导入错误:“Route”未从“react-router-dom”导出