如何在React组件prop更改时获取数据? [英] How to fetch data when a React component prop changes?

查看:468
本文介绍了如何在React组件prop更改时获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的TranslationDetail组件在打开时传递一个id,并在此基础上在类构造函数中触发外部api调用,接收数据到状态,并且此数据显示在TranslationDetail上。

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 this data being displayed on TranslationDetail.

//Routing:
<Route path="/translation/:id" component={TranslationDetail}/>

//Class:    
class TranslationDetail extends Component {
  constructor(props){
    super(props);

    this.props.fetchTrans(this.props.params.id);
  }

如果我手动输入网址,这一切都正常。如果我想使用react-router,例如为了显示下面的项目,如下所示,网址确实发生变化,但未触发api调用,数据将保持不变。

This all works fine if I enter the url manually. In case I'd like to use react-router e.g. for displaying the next item like below the url does change, but the api call is not triggered, and the data will remain the same.

<button 
  type="button"
  onClick={() => 
    browserHistory.push(`/translation/${Number(this.props.params.id)+1}`)}>
  Next
</button>

请记住,我是初学者。发生这种情况的原因是我认为构造函数只运行一次,因此不会触发进一步的api调用。

Please bear in mind that I'm a total beginner. The reason why this is happening is I believe that the constructor is run only once, thus no further api call is triggered.

我该如何解决这个问题?
我是否需要列出道具并在变更时调用函数?如果是,怎么做?

How can I solve this? Do I need to listed to props and call a function on change? If yes, how?

推荐答案

构造函数不是进行API调用的正确位置。

Constructor is not a right place to make API calls.

您需要使用生命周期事件:

You need to use lifecycle events:


  • componentDidMount 运行初始提取。

  • < a href =https://reactjs.org/docs/react-component.html#componentdidupdate =noreferrer> componentDidUpdate 电话。

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

确保将道具与 componentDidUpdate 中的先前道具进行比较如果你关心的特定道具没有改变,就避免取物。

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);
   }
}

这篇关于如何在React组件prop更改时获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆