首页 > 解决方案 > 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 并在每个函数运行/完成后更新状态。现在的问题是,每次我延迟这样的操作时,我都会延迟向用户显示数据。最终,这加起来并且很明显。因此,用户看到转动加载轮的时间增加了。

有没有另一种更快的方法来解决这个概念?

标签: reactjsredux

解决方案


我相信您正在从您的操作中返回响应有效负载并抛出错误。你得到你解决的承诺是then这样的:

componentDidMount() {
this.props.dispatch(fetchUsersOfList()).then((response)=>{
if (// your condition goes here") {
    ...
  }
 })
}

随时问任何问题


推荐阅读