【问题标题】:Expensive function blocks render() update昂贵的功能块 render() 更新
【发布时间】:2019-12-10 04:22:17
【问题描述】:

在我的(类)组件中,我想在 _expensiveFunction 期间显示加载微调器。 值isLoading在函数执行前的状态发生了变化,但在_expensiveFunction完成之前不会重新渲染(spinner不旋转)。

我用 componentDidUpdate 和 forceUpdate 尝试过,但没有成功。

_makeCalculation() {
  this.setState(
    { isLoading: true },
    () => this._expensiveFunction(),
  );
}


_expensiveFunction() {
  console.log(this.state.isLoading); // => true
  // ***
  this.setState({ isLoading: false });
}

【问题讨论】:

  • 您好,您能否分享一下您如何使用isLoading 的代码,在获取数据后让您的setState 函数像您在_makeCalculation 中所做的那样同步
  • 为什么不将expensiveFunction中昂贵部分之前的状态设置为isLoading: true
  • @devserkan 试过了,但没有成功。

标签: reactjs rerender


【解决方案1】:

一个常见的技巧是依赖setTimeout()

_makeCalculation() {
  this.setState(
    { isLoading: true },
    () => setTimeout(this._expensiveFunction, 0),
  );
}

【讨论】:

  • 这行得通,你能解释一下为什么吗?还有其他解决方案还是我必须坚持使用 setTimeout?
  • Javascript 是单线程的。如果一个事件被触发,它只能在当前运行的代码完成后运行。使用具有零时间延迟的 setTimeout 可以有效地告诉 JS 解释器回调函数调用是新上下文的一部分,并且您当前的代码块已完成。这意味着 JS 在调用 callback() 之前会趁机检查是否有其他事件需要处理。
猜你喜欢
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
相关资源
最近更新 更多