I'm studying React and find some confusing thing with setState.
Let's say our state's object has property(todos) === array with objects. I create handleChange function to change state. Here's trickiest part.
handleChange creates another array inside 'arrPrev' - which is clone of original state(no reference), then i change something in 'arrPrev' -> '+= 1', and return empty object in handleChange.
Why second div in render '{this.state.todos[0].text}' change it's data and re-render, but i returned empty object above and didn't change anything in state.
import React from "react"
class App extends React.Component {
constructor() {
super()
this.state = {
todos: [
{
id: 1,
text: "Take out the trash",
completed: true
},
{
id: 2,
text: "Grocery shopping",
completed: false
},
{
id: 3,
text: "Clean gecko tank",
completed: false
},
{
id: 4,
text: "Mow lawn",
completed: true
},
{
id: 5,
text: "Catch up on Arrested Development",
completed: false
}
]
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState(prevState => {
let arrPrev = prevState.todos.slice();
arrPrev[0].text += '1';
return {}
})
}
render() {
return (
<div className="todo-list">
<div onClick={this.handleChange}>{this.state.todos[0].id}</div>
<div>{this.state.todos[0].text}</div>
<div>{this.state.todos[0].completed}</div>
</div>
)
}
}
export default App