Reputation: 257
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 })
}
});
};
...
}
Upvotes: 2
Views: 105
Reputation: 3913
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
Upvotes: 0
Reputation: 358
Why dont you try this
this.setState((prevState, props) => {
//add your stuff here by matching it with previous state
})
Upvotes: 1