2017-12-01 7 views
0

잠시 동안 요소 중 하나를 렌더링해야하는 양식이 있습니다. 나는 componentDidMount에서이 목표를 위해 setTimeout를 사용하지만 구성 요소는 아마, 어떤 시점에서 다음 시간 제한이 종료 마운트 해제됩니다 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.React js 지연 렌더링 오류가 발생합니다.

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> 
     ); 
    } 
} 

답변

2

경고 얻을, 그것은 구성 요소가 더 이상 렌더링되는 후 setState를 호출하지하려고 시도합니다.

실행중인 시간 초과를 componentWillUnmount에서 취소해야합니다. 그들에 대한 참조를 저장하고 삭제하십시오.

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

감사! 내 문제를 해결하는 데 도움이되었습니다. – MyName

0

이는 setTimeout이 호출 될 때 구성 요소가 없기 때문일 수 있습니다. 마운트 된 플래그를 사용하여 구성 요소가 여전히 존재하는지 확인하십시오.

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); 
    } 
} 
관련 문제