React 功能组件访问整个状态

发布于 2025-01-19 10:17:38 字数 147 浏览 0 评论 0原文

在经典组件中,整个状态可作为单个对象 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌伤ぢ 2025-01-26 10:17:38

不,您无法访问包含您通过 useState 设置的所有状态成员的统一状态对象。

如果您愿意,您可以将所有组件状态存储在单个对象中(这甚至在 useState 文档 在谈论回调更新时)。例如:

const [state, setState] = useState({
    name: "",
    profession: "",
    age: null,
    // ...
});

要更新任何单个状态成员,您必须自己处理创建整个新对象(useState 中的状态设置器不会进行 Component.prototype.setState 的合并> 确实)。例如,设置年龄

setState(state => ({
    ...state,
    age: 42,
}));

使用回调形式非常重要(根据现有状态设置状态时总是如此)。

但除非您这样做,否则您无法访问任何单个对象。

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:

const [state, setState] = useState({
    name: "",
    profession: "",
    age: null,
    // ...
});

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 that Component.prototype.setState does). For instance, setting the age:

setState(state => ({
    ...state,
    age: 42,
}));

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文