簡體   English   中英

如何在 React 中使用 getDerivedStateFromProps 而不是 componentWillReceiveProps

[英]how to use getDerivedStateFromProps instead of componentWillReceiveProps in React

我喜歡更新我的代碼以使用 getDerivedStateFromProps 而不是 componentWillReceiveProps,因為我收到了已棄用的錯誤。 該組件正在接收一個日期屬性,每次更改日期時都需要使用新日期運行 getList。 為此,我使用下面的代碼

componentWillReceiveProps(nextProps) {
    const {date} = this.props;
    if (nextProps.date !== date) {
      console.log('prop changed to : ', nextProps.date);
      this.getList(nextProps.date);
    }
  }

我嘗試了以下但它不起作用

static getDerivedStateFromProps(props, state) {
    const {date} = this.props;
    if (props.date !== date) {
      console.log('prop changed to : ', props.date);
      this.getList(props.date);
    }
    return;
  }

getDerivedStateFromProps看起來不像是您要執行的操作的正確工具。 而是使用componentDidUpdate

componentDidUpdate(prevProps) {
  const { date } = this.props;
  if (prevProps.date !== date) {
    this.getList(date);
  }
}

很少使用getDerivedStateFromProps 有關何時使用getDerivedStateFromProps的更多信息,我推薦這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM