将类组件转换为功能组件

时间:2021-02-23 14:12:16

标签: reactjs

我正在更新一个旧的 React 应用程序并将数百个旧组件转换为新组件。我用 static 函数和 componentDidCatch 遇到了障碍,我知道它不再有钩子了。如何将此类升级为函数?

原始函数

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

  static getDerivedStateFromError(_error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    sendError("ErrorBoundary", { info }, error);
  }

  render() {
    if (this.state.hasError) {
      return <ErrorText />;
    } else {
      return this.props.children;
    }
  }
}

export default ErrorBoundary;

这是我目前所拥有的

const ErrorBoundary = (props) => {
  const [error, hasError] = useState(false)

  // code is unreachable
  ErrorBoundary.getDerivedStateFromError = (_error) => { 
    hasError(true)
    return error;
  }

  // cant use this lifecycle piece
  componentDidCatch(error, info) {
     sendError("ErrorBoundary", { info }, error);
  }

  if (error) {
    return <ErrorText />;
  } else {
    return props.children;
  }
}

0 个答案:

没有答案