werwe werwer
werwe werwer

Reputation: 25

Why prevProps always the same to current props in componentDidUpdate?

I have parent component with the local state like this:

this.state = {
  person: null
}

And when component renders the person becomes an object with different properties:

person = {
  id: 0,
  age: 20,
  name: 'John'
}

I passed this.state.person to child component, and I want to render it when person has another id.

if (!prevProps.person) {
            if (this.props.person) {
                this.fetchData(this.props);
                return;
            } else {
                return;
            }
        }
        if (
            this.props.person &&
            this.props.person.id !==
            prevProps.person.id
        ) {
            this.fetchData(this.props);
 }

It doesn't work, because prevProps always is equalt to this.props. How I can fix this?

Upvotes: 0

Views: 2918

Answers (2)

Yan Tsishko
Yan Tsishko

Reputation: 14

It depends on how you change your state and person object in it. See the example here, it works correctly.

The first state doesn't have any id, so you get an error. In case if you have some person id and then change the state to new data it's should be new object with a new reference

class Person extends React.PureComponent {
  componentDidUpdate(prevProps) {
   if (prevProps.person !== null && (prevProps.person.id !== this.props.person.id)) {
      console.log('it works');
    }
  }
  
  render() {
    const { person } = this.props;
    return (
      <>
        {person && person.name}
      </>
    );
  }
}

class A extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      person: null
    }
  }
  
  componentDidMount() {
    setTimeout(() => {
      this.setState({
        person: {
          id: 0,
          age: 20,
          name: 'John'
        }
      })
    }, 1000);
  }
  
  render() {
    const { person } = this.state;
    return (
      <>
        <Person person={person} />
      </>
    );
  }
}

ReactDOM.render(
    <A />,
    document.getElementById('root')
);

Upvotes: 0

Suhag Lapani
Suhag Lapani

Reputation: 695

You can use condition like this if (prevProps.person !== this.person)

            if (this.props.person) {
                this.fetchData(this.props);
                return;
            } else {
                return;
            }
        }
        if (
            this.props.person &&
            this.props.person.id !==
            prevProps.person.id
        ) {
            this.fetchData(this.props);
 }

Upvotes: 0

Related Questions