React's setState method with prevState argument

后端 未结 4 1055
野的像风
野的像风 2020-12-15 05:57

I\'m new to React, just have a question on setState method. Let\'s say we have a component:

class MyApp extends React.Component {

  state = {
    count: 3
          


        
4条回答
  •  隐瞒了意图╮
    2020-12-15 06:48

    Both signatures can be used, the only difference is that if you need to change your state based on the previous state you should use this.setState(function) which will provide you a snapshot(prevState) from the previous state. But if the change does not rely on any other previous value, then a shorter version is recommended this.setState({prop: newValue})

    this.setState(prevState =>{
       return{
            ...prevState,
            counter : prevState.counter +1
       }
    })
    
    this.setState({counter : 2})
    

提交回复
热议问题