簡體   English   中英

使用prop更新組件的狀態

[英]Updating component's state using props

我試圖以這種方式使用收到的道具來更新某些組件的狀態:

componentWillReceiveProps(nextProps) {
   if(nextProps.history.length <= 2) {
      this.setState({
         history: nextProps.history
      });
   }
}

問題在於,當父級傳遞的歷史記錄長度大於2時,狀態仍在變異。 有任何想法嗎?

謝謝

生命周期方法componentWillReceiveProps已棄用。 您應該使用getDerivedStateFromProps

在初始安裝和后續更新上,都在調用render方法之前立即調用getDerivedStateFromProps。 它應該返回一個對象以更新狀態,或者返回null則不更新任何內容。

您可以使用componentDidUpdate()生命周期方法或靜態的getDerivedStateFromProps()方法。

static getDerivedStateFromProps(props, state) {
    return ({
        history: props.history.length <= 2 ? props.history : state.history
    })
}

或者,如果您喜歡:

componentDidUpdate(prevProps) {
    const { history } = this.props;
    if((prevProps.history !== history) && history.length <= 2) {
        this.setState({ history })
    }
}

暫無
暫無

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

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