小编典典

React组件prop更改时如何获取数据?

reactjs

我的TranslationDetail组件在打开时会传递一个ID,并基于此ID在类构造函数中触发外部api调用,以接收到该状态的数据,并将此数据显示在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调用未触发,并且数据将保持不变。

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

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

我该如何解决?我是否需要列出道具并在更改时调用函数?如果是,怎么办?


阅读 336

收藏
2020-07-22

共1个答案

小编典典

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

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

componentDidUpdate如果您关心的特定道具没有变化,请确保将这些道具与以前的道具进行比较,以免获取。

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);
   }
}
2020-07-22