Created
August 17, 2016 02:10
-
-
Save irae/1255fe32277a88441d92c416651a5e8b to your computer and use it in GitHub Desktop.
Common React Mistake: Derivative State
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
var MyClassProps = React.createComponent({ | |
propTypes: { | |
email: React.PropTypes.string | |
}, | |
shouldComponentUpdate: function(nextProps) { | |
return this.props.email !== nextProps.email; | |
}, | |
render: function() { | |
var email = this.props.email; | |
var userDomainParts = email.split('@'); | |
return ( | |
<span className="email"> | |
<span className="user">{userDomainParts[0]}</span> | |
<span className="at">@</span> | |
<span className="domain">{userDomainParts[1]}</span> | |
</span> | |
); | |
} | |
}); | |
var MyClassState = React.createComponent({ | |
propTypes: { | |
email: React.PropTypes.string | |
}, | |
getInitialState: function() { | |
return {email: this.props.email}; | |
}, | |
componentWillReceiveProps: function(nextProps) { | |
if (this.props.email !== nextProps.email) { | |
this.setState({email: this.props.email.split('@')}); | |
} | |
}, | |
render: function() { | |
var userDomainParts = this.sate.email; | |
return ( | |
<span className="email"> | |
<span className="user">{userDomainParts[0]}</span> | |
<span className="at">@</span> | |
<span className="domain">{userDomainParts[1]}</span> | |
</span> | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment