Safe to set on this.state just to keep track?
I was wondering if it is safe to set .state
when I need to keep track.
My component, allows user to click it, every time they do it increments tieId
. On mouse exit of the component, if the tieId
is different from when they mouse enetered the component, I want to do a save.
I had to keep track on this.state
Is this code approptiate or will it break the React diff checking as I didn't use this.setState{tieId: ...}
?
var HelloMessage = React.createClass({
getInitialState: function() {
return {tieId: -1, onEnt: -1};
},
click: function(e) {
this.state.tieId++;
if (this.state.tieId > 2) {
this.state.tieId= -1;
}
},
mouseEnter: function(e) {
this.state.onEnt = this.state.tieId
},
mouseLeave: function(e) {
if (this.state.tieId != this.state.onEnt) {
alert('ok saving');
} else {
alert('will not save because tie id is same as when entered \n tieId: ' + this.state.tieId + ' \n onEnt: ' + this.state.onEnt);
}
},
render: function() {
return <div onClick={this.click} onMouseLeave={this.mouseLeave} onMouseEnter={this.mouseEnter} >Hello </div>;
}
});
ReactDOM.render(<HelloMessage />, mountNode);
Can copy paste this code at the React site Live JSX editor - http://facebook.github.io/react/
Answer
You should always use setState()
to make changes to your component state in React.
In case you don't believe me, here's Dan Abramov saying the same thing :)
(There's an exception if you're using ES6 classes: your constructor should set state
directly.)
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?