Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State not updating when receiving new props (ReactJS)

Tags:

reactjs

I'm new to React. I'm stuck on this, would really appreciate some help!

A parent component will pass an array into this child component. When I console.log(this.props.repairs) it shows me an array of 4. I am trying to update this.state.sortedDataList whenever the array of repairs is passed in. The console.log(this.state) is still showing sortedDataList as an empty array.

What am I doing wrong? Thanks so much, appreciate any help.

class Repairs extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      sortedDataList: []
    };
  }

  componentWillReceiveProps(nextProps) {
    if(this.props != nextProps) {
      this.setState({
        sortedDataList: this.props.repairs
      });
    }
  }

  render() {
    console.log(this.props);
    console.log(this.state);

    return (
      <div></div>
    );
  }
}
like image 606
Irene Li Avatar asked Jan 11 '17 03:01

Irene Li


People also ask

Why is React not updating on state change?

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.

Why isn't my React component updating?

There are two common reasons why React might not update a component even though its props have changed: The props weren't updated correctly via setState. The reference to the prop stayed the same.

How do you make sure state is updated in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.

Do React components update when props change?

By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate() .


1 Answers

Never mind, found my silly mistake! If anyone else gets stuck on this in the future...

componentWillReceiveProps(nextProps) {
  if(this.props != nextProps) {
    this.setState({
      sortedDataList: nextProps.repairs
    });
  }
}
like image 139
Irene Li Avatar answered Oct 26 '22 01:10

Irene Li