Hi, I just start learning react, and I am in the ‘state’ part now,
I just want to confirm on what I understand,
The React will trigger the re-render(replacing the Virtual DOM to the Real DOM) when the Virtual DOM has changed.
In more details, State is encapsulated, we cannot able to modify it unless we changes the props in the state.
The following code are from the https://daveceddia.com/why-not-modify-react-state-directly/
class App extends Component {
// Initialize items to an empty array
state = {
items: []
};
// Initialize a counter that will increment
// for each item ID
nextItemId = 0;
makeItem() {
// Create a new ID and use
// a random number as the value
return {
id: this.nextItemId++,
value: Math.random()
};
}
// The Right Way:
// copy the existing items and add a new one
addItemImmutably = () => {
this.setState({
items: [...this.state.items, this.makeItem()]
});
};
// The Wrong Way:
// mutate items and set it back
addItemMutably = () => {
this.state.items.push(this.makeItem());
this.setState({ items: this.state.items });
};
render() {
return (
<div>
<button onClick={this.addItemImmutably}>
Add item immutably (good)
</button>
<button onClick={this.addItemMutably}>Add item mutably (bad)</button>
<ItemList items={this.state.items} />
</div>
);
}
}
The Code above will have two buttons to demonstrate why modifying the state object won’t trigger the re-render.
When pressing AddItemImmutably button, it will work as expected that adding new element into the array.
When pressing the AddItemMutably button, it won’t work; it doesn’t add any elements
From what I understand, the items:[] inside the state is called props
state = {
items:[]
};
About the Right Way, because the code changing the state props (items:[]), so it works.
However, in the Wrong way,
this.state.items.push(this.makeItem());
this.setState({ items: this.state.items });
Since the state is already encapsulated and using the push method will get prevented by the React?
So actually the first line won’t do anything. Since the items didn’t get any changes and the second line will just assigning the same items, that’s why it won’t add new elements into the array.
One more example,
class App extends React.Component {
constructor() {
super()
this.state = {
count: 0
}
}
handleClick() {
this.state.count++
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.handleClick}>Change!</button>
</div>
)
}
}
The above code have a button that pressing it will increase the counter count.
Same situation, because we modify the count directly, so it get prevent by the react and it won’t work.
Sorry for long long paragraphs and Thanks