简体   繁体   中英

React functional component access entire 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM