How to fetch data when a React component prop changes?

前端 未结 4 1186
孤街浪徒
孤街浪徒 2020-12-04 16:30

My TranslationDetail component is passed an id upon opening, and based on this an external api call is triggered in the class constructor, receiving data to the state, and t

4条回答
  •  感情败类
    2020-12-04 17:14

    From React 16.3 and onwards componentWillMount, componentWillUpdate and componentWillReceiveProps are deprecated.

    You can use static getDerivedStateFromProps and return a new state based on changes on props.

    You don't have access to your this objects like props, so you cannot compare nextProps with your current props by nextProps.sth !== this.props.sth. You can compare you prevState value with nextProps and return new value of state.

    Make sue you add UNSAFE_ to your current componentWillMount and the other deprecated lifecyle methods for now.

提交回复
热议问题