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

bal*_*000 45 javascript reactjs react-router

我的TranslationDetail组件在打开时传递一个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);
  }
Run Code Online (Sandbox Code Playgroud)

如果我手动输入网址,这一切都正常.如果我想使用react-router例如显示下面的项目,如下所示,url确实会更改,但api调用不会被触发,并且数据将保持不变.

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

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

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

Yur*_*nko 86

构造函数不是进行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);
   }
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*vin 6

从阵营16.3及以后componentWillMount,componentWillUpdatecomponentWillReceiveProps弃用.

您可以使用static getDerivedStateFromProps并根据props上的更改返回一个新状态.

您无权访问像道具这样的对象,因此您无法nextProps与当前props的对象进行比较nextProps.sth !== this.props.sth.您可以比较您的prevStatenextProps并返回状态的新值.

立即起诉你添加UNSAFE_到当前componentWillMount和其他已弃用的生命周期方法.