简体   繁体   中英

this.setState inside the callback of this.setState not setting state

I have 2 list items which uses the same <ListItem /> component with this.props.a = true and this.props.b = true passed to it from a parent component (mentioning there are 2 because I am not sure that messes with anything but each of them should have their own independent component state).

In the <ListItem /> component I have an _handleOnClick function. When the _handleOnClick function is fired, inspecting the component state shows a: false and b:true although I see got here logged in my console.

I would have expected this.setState({ b: false }) to be called in the callback and the state to change to a: false and b:false . What am I missing?

export default class ListItem extends PureComponent {
    state = {
        a: this.props.a, //this.props.a is true
        b: this.props.b, //this.props.b is true
    };

    _handleOnClick = () => {
        this.setState({ a: !this.state.a }, () => {
            if (!this.state.a && this.state.b) {
                console.log('got here')
                this.setState({ b: false })
            }
        });
    };

...
}

Why dont you try this

this.setState((prevState, props) => {
//add your stuff here by matching it with previous state
})

Why are you setting derived state from props? I believe it's considered an anti-pattern to store anything in a state that can be derived from props at any point in time.

also https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

That being said, I believe your first argument is supposed to be the full state object. what-is-the-difference-between-passing-an-object-or-a-function-in-setstate

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