当 Reactjs 组件中的 componentWillUnmount 时如何清除异步函数?
How to clearTimeout an async function when componentWillUnmount in a Reactjs component?
组件如下:
class ChartComp extends Component{
constructor(props){
super(props);
this.timer = null;
this.loadData = this.loadData.bind(this);
}
componentWillMount(){
this.loadData();
}
componentWillUnmount(){
if(this.timer){
clearTimeout(this.timer);
}
}
loadData(){
//...
getJSON(url, msg=>{ //get data from server
if(msg.success){
//...
this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
}
})
}
render(){
//...
}
}
clearTimeout 函数将在卸载组件之前调用。但是计时器处于异步功能中,在我收到服务器响应后它会再次启动。那么我怎样才能让 clearTimeout 起作用呢?
在你的 class 里面设置一个标志 componentWillUnmount
.
在您的异步回调中,检查该标志是否已设置,如果已设置,请立即停止。
您当然可以按照@SLaks 的建议设置一个标志。这类似于 isMounted 模式。 ** 请注意,我更改为 componentdidmount,我认为这是一个更好的模式 **
class ChartComp extends Component{
constructor(props){
super(props);
this.timer = null;
this.loadData = this.loadData.bind(this);
}
componentDidMount() {
this._mounted = true;
this.loadData();
}
componentWillUnmount(){
this._mounted = false;
if(this.timer){
clearTimeout(this.timer);
}
}
loadData(){
//...
getJSON(url, msg=>{ //get data from server
if(msg.success && this._mounted){
//...
this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
}
})
}
render(){
//...
}
}
您可以进一步了解该模式为何被弃用 here
然而,天真地这样做最终需要在 getJSON 和随后的超时上都有标志,因为基本上你需要将可取消的承诺链接在一起(你想要停止任何步骤的地方)
要考虑的另一种范例是为此使用可观察链。有关详细信息,请参阅此 blog
组件如下:
class ChartComp extends Component{
constructor(props){
super(props);
this.timer = null;
this.loadData = this.loadData.bind(this);
}
componentWillMount(){
this.loadData();
}
componentWillUnmount(){
if(this.timer){
clearTimeout(this.timer);
}
}
loadData(){
//...
getJSON(url, msg=>{ //get data from server
if(msg.success){
//...
this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
}
})
}
render(){
//...
}
}
clearTimeout 函数将在卸载组件之前调用。但是计时器处于异步功能中,在我收到服务器响应后它会再次启动。那么我怎样才能让 clearTimeout 起作用呢?
在你的 class 里面设置一个标志 componentWillUnmount
.
在您的异步回调中,检查该标志是否已设置,如果已设置,请立即停止。
您当然可以按照@SLaks 的建议设置一个标志。这类似于 isMounted 模式。 ** 请注意,我更改为 componentdidmount,我认为这是一个更好的模式 **
class ChartComp extends Component{
constructor(props){
super(props);
this.timer = null;
this.loadData = this.loadData.bind(this);
}
componentDidMount() {
this._mounted = true;
this.loadData();
}
componentWillUnmount(){
this._mounted = false;
if(this.timer){
clearTimeout(this.timer);
}
}
loadData(){
//...
getJSON(url, msg=>{ //get data from server
if(msg.success && this._mounted){
//...
this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
}
})
}
render(){
//...
}
}
您可以进一步了解该模式为何被弃用 here 然而,天真地这样做最终需要在 getJSON 和随后的超时上都有标志,因为基本上你需要将可取消的承诺链接在一起(你想要停止任何步骤的地方)
要考虑的另一种范例是为此使用可观察链。有关详细信息,请参阅此 blog