reactjs - 我需要帮助将反应类组件转换为反应钩子
问题描述
我是反应钩子的初学者,我也在我的项目中使用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 钩子添加到其中。
谢谢
解决方案
在这种情况下,您需要知道的唯一 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 文档以获取更多参考信息。
推荐阅读
- excel - 如何在模块中使用 ActiveSheet 属性
- mysql - exec: \"mysql\": $PATH 中找不到可执行文件": 未知
- java - 通过 Weka、Java 运行 NBTree 和随机森林时出错
- mysql - 在 MySQL 和 PHP 中将两条记录与一个公共字段合并并增加一个字段
- asp.net-mvc - AspNet Core 2 No service for type 'Microsoft.AspNetCore.Http.HttpContext' 会话问题
- actions-on-google - Actions on Google:如何使用 NodeJS 实现数据库和用户实体(会话)
- ios - 如何在 ios-charts 上添加长按?
- javascript - 如何从值0到1获得从红色到白色的平滑渐变值?
- javascript - CSS 转换仅在 Chrome 开发工具打开时有效
- javascript - 使用 jQuery 设置整个选择值