React Hook: setState usage

眉间皱痕 提交于 2021-02-17 05:29:21

问题


What's the difference between

1

const [state, setState] = useState(0)

setState(state+1)

2

const [state, setState] = useState(0)

setState(...prevState => prevState+1)

回答1:


In the first option, based on the documentation:

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

In the second option, called functional update:

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

So basically if you'd like to be sure your state will be updated based on the previous state, you need to use the second option.

Read further in the official documentation of useState.

I hope this clarifies!



来源:https://stackoverflow.com/questions/63058656/react-hook-setstate-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!