2017-10-23 5 views
0

componentDidCatch 호출 받고되지

는 "응용 프로그램이 실수로 삼킨 경우에도 16 인쇄를 개발 콘솔에 렌더링하는 동안 발생한 모든 오류 반응라는 새로운 react 16 release doc 당으로 . "

은 내가 부모 구성 요소와 아이 구성 요소를 가지고있다. 나는 약속의 블록에서 오류를 일으켰다. 그러나 그것은 약속의 캐치 메소드를 호출 할 것이고, 부모의 componentDidCatch는 호출되지 않을 것이다. 이것이 예상 된 행동인지 여부는 확실하지 않습니다. 에 가져 당신이 .catch을 제거 할 경우, 더 이상 오류가 발생하지 않도록 다음

는 jsfiddle https://jsfiddle.net/john1jan/Luktwrdm/14/

class Parent extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state={hasError:false} 
    } 

    render() { 
    if(this.state.hasError){ 
     return <div>Something went wrong</div> 
    } 

    return (
     <div> 
     <h1>I am parent</h1> 
     <Child></Child> 
     </div> 
    ); 
    } 
    componentDidCatch(error,errorInfo){ 
    this.setState({ 
     hasError:true 
    }) 
    } 
} 

class Child extends React.Component { 

    render() { 
    return (
     <div> 
     <h1>I am child</h1> 
     </div> 
    ); 
    } 

    componentDidMount(){ 
    fetch("https://jsonplaceholder.typicode.com/posts").then((response) => { 
     throw new Error("I am the error in promise"); 
    }).catch((error)=>{ 
     console.log("Error caught in catch",error); 
    }) 
    ; 
    } 
} 

ReactDOM.render(<Parent name="world"/>, 
document.getElementById('container')); 
+1

오류가 구성 요소에 없으므로 잡을 것이 없습니다. 사실, 이미 예외를 잡았고 콘솔에 기록하도록 선택했습니다. 전달하려면 캐치에 오류를 다시 던지십시오. –

+0

오류가 구성 요소 수명주기 방법에 있습니까? – John

+0

의사는 "React 16은 렌더링 도중 발생한 모든 오류를 실수로 응용 프로그램을 삼켜 버린 경우에도 개발 중 콘솔에 인쇄합니다."라고 설명합니다. 그 후에 catch 블록을 추가하는 것을 잊어 버리면 어떻게 될까요? – John

답변

0

오류 및 캐치의 반환을 잡기있어 약속이입니다 componentDidMount에서 이것이 작동합니다!