React 功能组件访问整个状态
在经典组件中,整个状态可作为单个对象 this.state = {}
使用,我想知道是否有类似的方法可以访问功能组件中的状态?您可以通过变量名称访问各个属性,但我想知道是否有一种方法可以立即访问所有属性,就好像它们存储在一个总体对象中一样,类似于类组件。
In a classical component the entire state is available as a single object this.state = {}
, I was wondering if there's a similar way you could access the state in a functional component? You can access individual properties via their variable names but I'm wondering if there's a way to access all of them at once as if they were stored in an overarching object, similar to a class component.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您无法访问包含您通过
useState
设置的所有状态成员的统一状态对象。如果您愿意,您可以将所有组件状态存储在单个对象中(这甚至在
useState
文档 在谈论回调更新时)。例如:要更新任何单个状态成员,您必须自己处理创建整个新对象(
useState
中的状态设置器不会进行Component.prototype.setState
的合并> 确实)。例如,设置年龄
:使用回调形式非常重要(根据现有状态设置状态时总是如此)。
但除非您这样做,否则您无法访问任何单个对象。
No, there's no consolidated state object you can get access to that has all of the state members you've set up via
useState
.You could store all of your component state in a single object if you want (this is even mentioned in the
useState
docs when talking about callback updates). For instance:To update any individual state member, you have to handle creating the entire new object yourself (state setters from
useState
don't do the merging thatComponent.prototype.setState
does). For instance, setting theage
:It's important to use the callback form (as is always the case when setting state based on existing state).
But unless you do that, no, there's no one single object you have access to.