From 465c8075dd648ab1dbb3052b665d9a581b5f4379 Mon Sep 17 00:00:00 2001 From: Maciej Czekaj Date: Wed, 24 Oct 2018 22:43:21 +0200 Subject: [PATCH] #9792 Migrate Button to new lifecycle methods Signed-off-by: Maciej Czekaj --- components/button/button.tsx | 40 +++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/components/button/button.tsx b/components/button/button.tsx index cf03e58fe7..2e09f99b48 100644 --- a/components/button/button.tsx +++ b/components/button/button.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; import * as PropTypes from 'prop-types'; import classNames from 'classnames'; +import { polyfill } from 'react-lifecycles-compat'; import Wave from '../_util/wave'; import Icon from '../icon'; import Group from './button-group'; @@ -74,7 +75,12 @@ export type NativeButtonProps = { export type ButtonProps = AnchorButtonProps | NativeButtonProps; -export default class Button extends React.Component { +interface ButtonState { + loading?: boolean | {delay?: number}; + hasTwoCNChar: boolean; +} + +class Button extends React.Component { static Group: typeof Group; static __ANT_BUTTON = true; @@ -97,6 +103,14 @@ export default class Button extends React.Component { block: PropTypes.bool, }; + static getDerivedStateFromProps(nextProps: ButtonProps, _prevState: ButtonState) { + if (nextProps.loading instanceof Boolean) { + return {loading: nextProps.loading} + } + + return null; + } + private delayTimeout: number; private buttonNode: HTMLElement | null; @@ -112,25 +126,23 @@ export default class Button extends React.Component { this.fixTwoCNChar(); } - componentWillReceiveProps(nextProps: ButtonProps) { - const currentLoading = this.props.loading; - const loading = nextProps.loading; + componentDidUpdate(prevProps: ButtonProps, _prevState: ButtonState) { + this.fixTwoCNChar(); - if (currentLoading) { + if (prevProps.loading && typeof prevProps.loading !== 'boolean') { clearTimeout(this.delayTimeout); } - if (typeof loading !== 'boolean' && loading && loading.delay) { - this.delayTimeout = window.setTimeout(() => this.setState({ loading }), loading.delay); + const { loading } = this.props; + if (loading && typeof loading !== 'boolean' && loading.delay) { + this.delayTimeout = window.setTimeout(() => this.setState({loading}), loading.delay); + } else if (prevProps.loading === this.props.loading) { + return; } else { - this.setState({ loading }); + this.setState({loading}); } } - componentDidUpdate() { - this.fixTwoCNChar(); - } - componentWillUnmount() { if (this.delayTimeout) { clearTimeout(this.delayTimeout); @@ -257,3 +269,7 @@ export default class Button extends React.Component { ); } } + +polyfill(Button); + +export default Button;