我是React钩子的初学者,我也在项目中使用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钩子。
谢谢
答案 0 :(得分:0)
在这种情况下,您只需要知道两个钩子是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 docs for hooks以获得更多参考。
答案 1 :(得分:0)
这可以转换为此,但是我建议为最终返回中的内容编写另一个组件,这将使您的代码更整洁。
const Detail = (props) => {
const { data, classes, siteId } = props;
const { sites } = data;
const { controller } = _.first(sites);
const [showDialog, setShowDialog] = useState(false);
const handleRowHistory = () => {
setShowDialog(true)
}
const dissmissDialog = () => {
setShowDialog(false)
}
if (data.error) {
return <CardErrorIndicator apolloData={data} />;
}
if (data.loading) {
return <CardLoadingIndicator />;
}
return (
<div
className={classNames(
classes.overall,
classes.basePadding,
"site-assets-detail-page"
)}
>
<SiteRowController
controller={controller}
onRowHistoryClick={handleRowHistory}
/>
{showDialog && (
<RowHistoryDialog
open={showDialog}
siteId={siteId}
onClose={dissmissDialog}
/>
)}
</div>
);
}
}