首页 > 解决方案 > 我需要帮助将反应类组件转换为反应钩子

问题描述

我是反应钩子的初学者,我也在我的项目中使用graphql。有人可以帮助将组件转换为反应钩子。

class Detail extends Component {
  static propTypes = {
    classes: PropTypes.shape(commonStyles).isRequired,
    siteId: PropTypes.string
  };
  state = {
    showDialog: false
  };
  handleRowHistory = () => {
    this.setState({ showDialog: true });
  };
  render() {
    const { showDialog } = this.state;
    const { data, classes, siteId } = this.props;
    if (data.error) {
      return <CardErrorIndicator apolloData={data} />;
    } else if (data.loading) {
      return <CardLoadingIndicator />;
    }
    const { sites } = data;
    const { controller } = _.first(sites);

    return (
      <div
        className={classNames(
          classes.overall,
          classes.basePadding,
          "site-assets-detail-page"
        )}
      >
        <SiteRowController
          controller={controller}
          onRowHistoryClick={this.handleRowHistory}
        />
        {showDialog && (
          <RowHistoryDialog
            open={showDialog}
            siteId={siteId}
            onClose={() => this.setState({ showDialog: false })}
          />
        )}
      </div>
    );
  }
}

const DetailWithData = compose(
  graphql(SITE_ASSETS_DETAIL_QUERY, {
    options: props => ({
      variables: {
        siteId: props.siteId
      },
      pollInterval: 5000
    })
  })
)(Detail);

export default withStyles(commonStyles)(DetailWithData);

我知道 React-Hooks 是 React Class 风格的替代品。问题是我是否可以重构并将 React 钩子添加到其中。

谢谢

标签: reactjsreact-hooks

解决方案


在这种情况下,您需要知道的唯一 2 个钩子是useState()useCallback()(可选)。对于道具类型,您可以单独声明它们。因此,结合所有这些,您的代码应该大致如下所示:

const Detail = ({ data, classes, siteId }) => {
  const [showDialog, setShowDialog] = useState(false);
  const handleRowHistory = () => {
    setShowDialog(true);
  }; // You might need to use useCallback to stop new functions from being created

  if (data.error) {
    return <ErrorComponent />;
  }
  if (data.loading) {
    return <LoadingComponent />;
  }

  return <YourComponent />;
};

Details.propTypes = {
  // Declare your prop types here
};

您可能想查看React 文档以获取更多参考信息。


推荐阅读