A
A
anxieter2019-07-22 20:08:45
React
anxieter, 2019-07-22 20:08:45

Understanding the React lifecycle coupled with getting data from the server?

Hello. Help me understand how the react lifecycle works.
The code contains the code of the component. At the moment of ComponentDidMount, the data is fetched, gets into the Redux store, from where it successfully gets into the props of the component.
In this example, curPrice is the props received from the server. amount - the props received from the parent component.
Next, I try to "catch" curPrice in the lifecycle methods, but it is displayed as it should.
Further questions go in the course of the code.

class Card extends Component {
  state = {
    newPrice: null,
  };

  componentDidMount() {
    const { fetchPrice } = this.props;
      fetchPrice(fetchType);
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log(this.props.curPrice); // undefined - почему????  - ведь мы curPrice передали
    // в this.props при рендере
    console.log(nextProps.curPrice); // {USD: 100} // а здесь они есть)) 
    return true;
  }

 // Тут я обновляю страницу и смотрю что приходит, или не поможет?...
  componentDidUpdate(prevProps, prevState) {
    console.log(prevProps.curPrice); // undefined  - почему???? 
  }

  static getDerivedStateFromProps(props, state) {
    console.log(props.amount); // видна с первого рендер
    console.log(props.curPrice); // видна сразу со второго render
    // Поэтому чтобы записать State - приходится делать дополнительную проверку, 
    //которую я нигде в примерах не встречал - это правильно?..
    if (props.curPrice) {
      return { newPrice: props.curPrice };
    } else return null;
  }

  render() {
    const { curPrice, amount } = this.props;
    return (...);
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    curPrice: state.prices.types[ownProps.idx],
  };
};

const mapDispatchToProps = {
  fetchPrice,
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Card);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-22
@anxieter

In this example, curPrice is the props received from the server

The componentDidMount lifecycle method is called after render.
It is not surprising that on the first render, instead of data, you get undefined no. At this point, your request to the server has not even been initiated yet.
Therefore, in order to write the State, you have to do an additional check,
which I have not seen anywhere in the examples - is that right? ..

It's not clear why you should use state at all. If you do not change this value in your component in any way, then use it directly from props.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question