-1

我有下面的代码。如何将它从类组件转换为功能组件,注意我想使用接口而不是类型?同样,我相信不需要空类型的道具,对吧?

import { v4 as uuidv4 } from 'uuid';

type Props = {};
type State = {
  hasError: boolean;
  guid: string;
};

export class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      hasError: false,
      guid: uuidv4(),
    };
  }

  render() {
    if (this.state.hasError) {
      return <>Error</>;
    }

    return this.props.children;
  }
}
}; 
4

1 回答 1

0

这个特定的组件可以写成这样的功能组件。

import { useState, ReactNode } from "react";
import { v4 as uuidv4 } from "uuid";

type Props = {
  children: ReactNode;
  otherProp?: string;
};

type State = {
  hasError: boolean;
  guid: string;
};

const ErrorBoundary = ({ children }: Props): JSX.Element => {
  const [state, setState] = useState<State>({
    hasError: false,
    guid: uuidv4()
  });

  if (state.hasError) {
    return <p>Error</p>;
  }

  return <>{children}</>;
};

const MyComp = () => {
  return <ErrorBoundary>some content without error</ErrorBoundary>;
};

export default MyComp;

编辑 dreamy-lederberg-s2r5u


笔记

如果您尝试按照 react 文档中的描述创建一个ErrorBoundary- 请注意,只能使用类组件

于 2021-09-01T10:12:43.797 回答