reactjs - 是否可以在 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);
}
}
}
解决方案
您不应允许 getDerivedStateFromProps 更改非静态变量或调用非静态方法。最好从那里返回新状态。我的建议是让您使用不同的生命周期方法,例如
componentDidUpdate(prevProps) {
// compare status props and clear timer
if (this.props.status === 'completed') {
clearInterval(this.intervalTimer);
}
}
为了安全起见,也要在里面清理
componentWillUnmount(){
clearInterval(this.intervalTimer)
}
推荐阅读
- amazon-web-services - 无法通过 SSH 或 FTP 访问 AWS EC2 Amazon Linux 实例:在 /var/www 中更改所有者后“网络错误:软件导致连接中止”
- flutter - 复选框未检查 showDialog 内颤动
- sql - ORA-00904: "NEW_SALARY": 无效标识符
- r - 如何在 macOS Big Sur 中安装 rgl 包
- symbolic-math - 在 Maxima 中代入微分方程
- angular - Nativescript/Angular 使用选项卡从一个功能模块导航到另一个功能模块
- java - E/PDFView: 加载 pdf 错误。java.io.FileNotFoundException:打开失败:ENOENT(没有这样的文件或目录)
- mips - MIPS 有什么理由不使用 li 而不是 lw 来存储整数、浮点数、双精度数?
- python - 从数据框条目中提取所有 10 位数字(文本)
- reactjs - Recoil DarkMosw