简体   繁体   中英

Is there an easier way to reset states in React?

My React app has a form to add a new product and each product has a number of properties. When the product is added I redirect the user to the saved products page, and they can edit any saved products. I've run into some (not major) issues with the states. In some areas when editing, the state displays another products attributes because it has not been updated.

I want to clear the state so that if a product attribute's state isn't updated it is simply an empty string. Right now I'm doing this:

const resetStates = () => {
    setName("");
    setDescription("");
    setPrice(null);
}   

These are only some of the states being used, so it's cumbersome to have to reset all of them like this. Is there an easier way?

You can aggregate the state properties into a single object, like class components' state.

[formContent, setFormContent] = useState({name:'',desc:'',price: null});


const resetStates = ()=> {
    setFormContent({name: '', desc: '', price: null});
}

However the react docs seem to slightly prefer the separate state variables over a single object, since unlike this.setState updating a state variable using hooks, replaces its value.

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