Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Broken componentWill(Did)Update #2974

Closed
LKay opened this issue Jan 29, 2015 · 5 comments
Closed

Broken componentWill(Did)Update #2974

LKay opened this issue Jan 29, 2015 · 5 comments

Comments

@LKay
Copy link

LKay commented Jan 29, 2015

When updating state of the component the corresponding method from lifecycle get called but every time for any component the prevState or nextState is in fact always the same with the current state. So comparing them always return true. Mentioned methods should return correct objects for previous, next state.

getInitialState: function () {
    return {
        test: false
    };
}
someMethod: function () {
    this.setState({
        test: true
    });
}
componentDidUpdate: function (prevProps, prevState) {
    console.log(prevState.test === this.state.test); // Always true!
},
@syranide
Copy link
Contributor

Your example correctly yields false for me (http://jsfiddle.net/xgdm73a3/).

However, I'm pretty sure the issue you're seeing has to do with mutating objects in state/props. React does not clone objects passed in to state/props, hence, both this.state.foo and prevState.foo will reference the same object. This is why React advocates sticking to "immutable data", i.e. always create a new object instead of mutating an existing.

@LKay
Copy link
Author

LKay commented Jan 29, 2015

Oh, yeah the problem occurs with objects, you are right, the example was not entirely complete. Anyway I do clone the object on assigning from props to component state either by doing JSON.parse(JSON.stringify(obj)) or using Underscore.js _.clone(). Problem still exists (http://jsfiddle.net/xgdm73a3/1/).

@syranide
Copy link
Contributor

Line 8, you're mutating the state object you try to compare.

@hzoo
Copy link
Contributor

hzoo commented Jan 29, 2015

this.state.test.state = true;
this.setState({
    test: this.state.test
});

Not sure why you need to manually set the state and then call setState - you should be able to do

this.setState({
    test: true
});

(http://jsfiddle.net/xgdm73a3/2/)

@zpao
Copy link
Member

zpao commented Jan 30, 2015

As noted, you're modifying this.state directly, which is what's used for prevState.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants