Created
February 14, 2020 09:44
-
-
Save Lelith/5a5d2250a2ba49db8d40bedb2c638a9d to your computer and use it in GitHub Desktop.
Call callback in componentDidUpdate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* src/components/Counter/index.js */ | |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import classNames from 'classnames/bind'; | |
import './index.css'; | |
class Counter extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
amount: this.props.amount | |
} | |
} | |
increaseAmount() { | |
this.setState(prevState => ( | |
{amount: prevState.amount +1}) | |
) | |
} | |
decreaseAmount() { | |
this.setState(prevState => ( | |
{amount: prevState.amount -1}) | |
) | |
} | |
componentDidUpdate(prevProps, prevState) { | |
if(prevState !== this.state) { | |
this.props.callBack(this.state.amount); | |
} | |
} | |
render() { | |
const { | |
amount, | |
callBack, | |
...other | |
} = this.props; | |
const counterClasses = classNames( | |
'counter', | |
); | |
return ( | |
<div className={counterClasses} {...other}> | |
<button aria-label='decrease' onClick={() => this.decreaseAmount()}> | |
- | |
</button> | |
<input type='text' readOnly value={this.state.amount} aria-label="current amount"/> | |
<button aria-label='increase' onClick={() => this.increaseAmount()}> | |
+ | |
</button> | |
</div> | |
); | |
} | |
} | |
Counter.propTypes = { | |
amount: PropTypes.number, | |
callBack: PropTypes.func.isRequired | |
}; | |
Counter.defaultProps = { | |
amount: 0 | |
}; | |
export default Counter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment