Как я могу проверить границу ошибки в производстве? - PullRequest
0 голосов
/ 06 ноября 2019

Я добавляю границу ошибки верхнего уровня в свое приложение. Локально все выглядит нормально, но я не уверен, как его протестировать в производстве, так как я не знаю никаких ошибок рендеринга. Есть ли способ заставить компонент реагирования выдавать ошибку в дикой природе? Или есть лучший способ убедиться, что граница ошибки делает то, что должна делать, без реальной ошибки?

1 Ответ

0 голосов
/ 06 ноября 2019

Допустим, у меня есть родительский компонент, у него два дочерних элемента, и каждый дочерний элемент заключен в ErrorBoundary. Если какая-либо ошибка возникает в каком-либо дочернем элементе, ErrorBoundary будет отображаться вместо дочернего элемента, у которого есть ошибка.

Parent.js

<Parent>
  <Child02 />
  <Child01 /> {/*It's a Setting icon, check out the pic below*/}
</Parent>

Child02.js

render(){
return(
<ErrorBoundary>
  <div>my custom components value </div>
  <ErrorComponent />
</ErrorBoundary>
);}

ErrorBoundary.js Вы можете изменить render то, что вы хотите показать своим пользователям ... и т. Д.

import React from "react";

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

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.log("my custom error: ", error, errorInfo);

    // logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

ErrorComponent.js Давайте добавим ошибку внутрь ErrorComponent

export default class ErrorComponent extends Component {
  render() {
    const x = 5;
    x = 7; //it will throw error, because we can't change a constant's value
    return <div>hello  
{/* some dynamic logic..etc which may cause Error in future */}
</div>;
  }
}

this is what my ErrorBoundary renders

Поскольку у компонента ErrorComponent есть ошибки, то Parent компонент будет отображать что-то вроде этого:

<Parent>
  <Child01 />
  <h1>Something went wrong.</h1> {/*this is what ErrorBoundary renders, it's coming from ErrorBoundary's render method*/}
</Parent>
...