首页 > 解决方案 > 是否可以在 React 的静态 getDerivedStateFromPRops 方法中使用 ClearInterval?

问题描述

我已经设置了一个间隔并在 ComponentDidMount 方法中做了一些操作。我想在完成 props.status 后清除间隔。

class A extends React.PureComponent {
 constructor(props) {
  super(props);
  this.intervalTimer = '';
}

componentDidMount() {
  this.intervalTimer = setTimeout(() => {
    // do something;
}, 3000);
}

static getDerivedStateFromProps(np, ps) {
 if(np.status === 'completed') {
  clearInterval(A.intervalTimer);
}
}
}

标签: reactjslifecycle

解决方案


您不应允许 getDerivedStateFromProps 更改非静态变量或调用非静态方法。最好从那里返回新状态。我的建议是让您使用不同的生命周期方法,例如

componentDidUpdate(prevProps) {
  // compare status props and clear timer
  if (this.props.status === 'completed') {
   clearInterval(this.intervalTimer);
  }
}

为了安全起见,也要在里面清理

componentWillUnmount(){
 clearInterval(this.intervalTimer)
}

推荐阅读