While looking through the ReactJS code of a colleague, I noticed them "modifying the state directly". I also tried it out with this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class App extends React.Component {
constructor(props) {
super(props);
this.state = {"message":""};
}
textChange(evt) {
this.state.message = evt.currentTarget.value;
this.setState({});
}
render() {
return (
<div>
<p>{this.state.message}</p>
<input type="text" onChange={evt=>this.textChange(evt)} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
</body>
</html>
The method textChange(evt)
consistently and reliably updates the state. I read in a few blogs on the internet that we should not be modify the state directly...did I misunderstand something?
Also consider all these other ways of modifying states:
textChange1(evt) {
this.state.message = evt.currentTarget.value;
this.setState(this.state);
}
textChange2(evt) {
const state = this.state;
state.message = evt.currentTarget.value;
this.setState(state);
}
textChange3(evt) {
const state = this.state;
state.message = evt.currentTarget.value;
this.setState({});
}
textChange4(evt) {
this.setState({message:evt.currentTarget.value});
}
textChange5(evt) {
let message = evt.currentTarget.value;
this.setState({message});
}
Which of these is the idiomatic way to modify states in ReactJS?