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

查看:43
本文介绍了当 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 例如用于显示 url 下面的下一个项目确实发生了变化,但不会触发 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:

确保将这些 props 与 componentDidUpdate 中之前的 props 进行比较,以避免在您关心的特定 props 没有改变的情况下获取.

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天全站免登陆