本文介绍了React Hook:setState 用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别

1

const [state, setState] = useState(0)设置状态(状态+1)

2

const [state, setState] = useState(0)setState(...prevState => prevState+1)
解决方案

在第一个选项中,基于 文档:

setState 函数用于更新状态.它接受一个新的状态值并将组件的重新渲染排入队列.

在第二个选项中,称为功能更新::>

如果新状态是使用之前的状态计算出来的,你可以传递一个函数给 setState.该函数将接收先前的值,并返回更新的值.

所以基本上如果你想确保你的状态会根据之前的状态更新,你需要使用第二个选项.

进一步阅读 useState.

我希望这能澄清!

What's the difference between

1

const [state, setState] = useState(0)

setState(state+1)

2

const [state, setState] = useState(0)

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

In the first option, based on the documentation:

In the second option, called functional update:

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!

这篇关于React Hook:setState 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:29