React Hook:setState 用法 [英] React Hook: setState usage

查看:217
本文介绍了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:

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!

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆