2017-12-01 1 views
0

Ich habe Formular, wo ich eines der Elemente in einer Weile rendern sollte. Ich benutze setTimeout für dieses Ziel in componentDidMount aber ich setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.Reaktion js Delay Rendering verursacht Fehler

class Form extends React.Component { 
    constructor(props, context) { 
     this.state = {resend: false}; 
    } 

    componentDidMount() { 
     const max = 3; 

     if (this.props.count < max) { 
      setTimeout(() => { 
       this.setState({resend: true}); 
      }, 1000); 
     } 
    } 

    render() { 
     return (
      <form> 
       ... 
       {this.state.resend ? <Component/> : null} 
      </form> 
     ); 
    } 
} 

Antwort

2

Ihre Komponente wahrscheinlich bekommen Warnung wird an einem gewissen Punkt Aushängen, dann die Timeout beendet, und es versucht, setState aufzurufen, nachdem die Komponente nicht mehr wiedergegeben wird.

Sie müssen alle ausgeführten Zeitüberschreitungen in componentWillUnmount abbrechen. Speichern Sie einen Verweis auf sie und löschen Sie sie.

class Form extends React.Component { 
    constructor(props, context) { 
     this.state = {resend: false}; 
     this.timeouts = []; 
    } 

    componentWillUnmount(props, context) { 
     this.timeouts.forEach(t => window.clearTimeout(t)); 
    } 

    componentDidMount() { 
     const max = 3; 

     if (this.props.count < max) { 
      const timeoutId = setTimeout(() => { 
       this.setState({resend: true}); 
      }, 1000); 
      this.timeouts.push(timeoutId); 
     } 
    } 

    render() { 
     return (
      <form> 
       ... 
       {this.state.resend ? <Component/> : null} 
      </form> 
     ); 
    } 
} 
+0

Vielen Dank! Es half mein Problem zu lösen – MyName

0

Dies liegt möglicherweise daran, dass die Komponente beim Aufruf von setTimeout nicht existiert. Verwenden Sie ein bereitgestelltes Flag, um festzustellen, ob die Komponente noch vorhanden ist.

constructor(props, context) { 
    this.state = {resend: false}; 
    this.mounted = true; 
} 

componentWillUnmount() { 
    this.mounted = false; 
} 

componentDidMount() { 
    const max = 3; 

    if (this.props.count < max) { 
    setTimeout(() => { 
     if (!this.mounted) return; 
     this.setState({resend: true}); 
    }, 1000); 
    } 
}