Status is not updated when new details are received (ReactJS)

I am new to React. I am stuck on this, I would really appreciate help!

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

What am I doing wrong? Thanks a lot, 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>
    );
  }
}
+6
source share
3 answers

Nothing, found my stupid mistake! If anyone else gets stuck in this in the future ...

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

componentWillReceiveProps .

React Docs:

", . .

, componentWillMount lifecycle . WillReceiveProps.

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

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

  componentWillMount() {
   
      this.setState({
        sortedDataList: this.props.repairs
      }, () => console.log(this.state.sortedDataList));
    
  }
   componentWillReceiveProps(nextProps) {
    if(this.props != nextProps) {
      this.setState({
        sortedDataList: nextProps.repairs
      });
    }
  }

  render() {
    console.log("r",this.props);
    console.log("r",this.state);

    return (
      <div></div>
    );
  }
}

class App extends React.Component {
  render() {
    var arr = ["1", "2", "3"];
    return (
      <div >
        <Repairs repairs={arr}/>
      </div>
    )
  }
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
Hide result
+1

this.state = {
  sortedDataList: []
};

, . , , , componentWillReceiveProps().

As Shubham said, the WillReceiveProps () component is not called in the first render. If you want the state to reflect props directly from the first rendering, you need to put it in the constructor as follows:

this.state = {
  sortedDataList: this.props.repair
};
0
source

Source: https://habr.com/ru/post/1013964/


All Articles