B
B
Bzeeng2021-02-18 22:32:41
React
Bzeeng, 2021-02-18 22:32:41

What for it is necessary to push through ...prev in setState?

Why do we need to add ...prev when changing the state, what's the point?

this.setState( prev => (  
            
                
                {
                    ...prev,
                    ...{
                    [e.target.name] : e.target.value
                    }
                }
                 
            )
          
        )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2021-02-18
@Casufi

I do not see the point in such a record, it is enough to write

this.setState({
  [e.target.name]: e.target.value
})

https://reactjs.org/docs/state-and-lifecycle.html

V
Viktor Zorin, 2021-02-18
@FutureAnge1

This may be needed in applications where the state transition is actively used (For example, using Ctrl + Z, but such an entry is optional, SetState() will copy all the fields of the previous state to the new one)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question