简体   繁体   中英

Can someone give a more real-world example where the setState(updaterFunc) function is more useful than the setState(object)?

the react docs said that is better to use the setState(updaterFunc) rather than the setState(object) because it will have the latest state. I know setState is async, that's why we use the setState(updaterFunc) to have the latest state. But in the example below I just can't wrapped my head around why should I use the setState(updaterFunc) when I can do it in one go with just the setState(object)

But I'm confused why should I do multiple setState calls rather than just doing it in one go.

this.setState((state) => ({ counter: state.counter + 1}));
this.setState((state) => ({ counter: state.counter + 1}));
this.setState((state) => ({ counter: state.counter + 1 }));

why not do it just like this?

this.setState({counter: 3});

When you perform setstate, the state is set asynchronously hence when you do it how react tells us to, as on state change, react detects change and re-renders.

Probably the best practice would be ,

this.setState((previousState, currentProps) => {
    return { ...previousState, foo: currentProps.bar };
});

If your new state depends on old state then updating via function is preferred. If your new state is not dependant on the old state then you can directly give an object.

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