How to fetch data when a React component prop changes?

前端 未结 4 1184
孤街浪徒
孤街浪徒 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 16:52

    Use componentWillMount to get the data and set the state. Then use componentWillReceiveProps for capturing update on the props.

    You can check the Component Specs and Lifecycle.

    0 讨论(0)
  • 2020-12-04 17:10

    I would use the render method. If the data is not loaded I would render a loader spinner and throw the action that fetch de data. For that i usually use the stores. Once the store has de data from the api, mark the data as loaded, throw an event and let the component get the data from the store, replacing the loader spinner with your data representation.

    0 讨论(0)
  • 2020-12-04 17:11

    Constructor is not a right place to make API calls.

    You need to use lifecycle events:

    • componentDidMount to run the initial fetch.
    • componentDidUpdate to make the subsequent calls.

    Make sure to compare the props with the previous props in componentDidUpdate to avoid fetching if the specific prop you care about hasn't changed.

    class TranslationDetail extends Component {    
       componentDidMount() {
         this.fetchTrans();
       }
    
       componentDidUpdate(prevProps) {
         if (prevProps.params.id !== this.props.params.id) {
           this.fetchTrans();
         }
       }
    
       fetchTrans() {
         this.props.fetchTrans(this.props.params.id);
       }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题