I want to Understand SetState and Prevstate in ReactJS

前端 未结 2 353
情话喂你
情话喂你 2021-01-22 13:27

I am new to ReactJS, I am using wizard form in my project which enable user to next and prev step. I copied some code for next button but honestly did\'t understand what it mean

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 13:55

    As I mentioned in my comment, you'll need to look into the docs itself to know more about how setState works.

    Further here, I want to specify why shall we need it?

    In react states are not mutable ie. to say you cannot change the state directly like:

    state = { current: 1 }
    // ...and somewhere in your code
    this.state.current = 2 // won't work
    this.state.current = this.state.current + 1 // also, no luck
    console.log(this.state.current) // 1
    // the reason is immutable
    

    So, you'll need to update the state without mutating it. And thus, react provides us publicly to use setState.

    setState has two arguments: updater and callback.

    The updater can accept state and props. So that you update the state checking its condition based on state and props or somehow else you'll want.

    The callback is provided here in the setState so you may know its effect like what the current is now. See an example below:

    this.setState((state, props) => { // previous state, previous props
      // you may additionally check some condition
      // or combine state and props
      // like, state.current + props.value
      return { current: state.current + 1 }
    }, () => {
    // ^^- callback
      console.log(this.state.current)
    })
    

    BTW, there are some different options to use the setState:

    a) without updater and callback
    eg. setState({current: 2})
    b) with updater param only
    eg. setState(()=>({current: 2}))
    c) with updater and callback
    eg. see preceding example of code
    d) without updater but with callback
    eg.  setState({current: 2},()=>console.log(this.state.current))
    

提交回复
热议问题