I want to Understand SetState and Prevstate in ReactJS

前端 未结 2 358
情话喂你
情话喂你 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 14:08

    Thanks for contributing.

    As has been suggested in the comments, you probably should take a look at the documentation, but since you are a new contributor, I thought I'd try to answer your question.

    How State and setState Work

    Every component react class has a "state." When "state" is updated, the component will re-render. setState is the method used to update the state of the component. this refers to the component itself.

    Your component state object might look like this initially: { current: 0, something: 'foo' }.

    What next() is doing

    When you call next(), then setState will also be called. setState is called with a callback. The callback provides an argument, here named prevState - prevState is the current state on the component, so { current: 0, something: 'foo' }.

    The return value of setState will set any fields on the state object that are provided. After calling this.setState, the new value of component.state will be { current: 1, something: 'foo' }.

    re-render

    A re-render of the component will be triggered because a shallow comparison of the new state and previous state objects will return false.

    Hope this helps!

提交回复
热议问题