2017-03-09 65 views
0

我正在使用其他人編寫的相當複雜的反應應用程序。我想爲消息線程末尾的表單字段設置一個默認值。管理componentwillrecieveprops和onChange功能之間的衝突

在加載所有數據之前,可能會調用子呈現函數多次。而我的表單組件的默認值取決於線程中的最後一個值。

出於這個原因,我設置在構造函數中replyType並有一定的邏輯getReplyType計算基於當前的道具:

constructor(props) { 
    super(props); 

    this.state = { 
     replyType: this.getReplyType(), 
    }; 
    } 

如果它之前花了3次,這不會使正確的價值我們從父母那裏獲得了所有的數據。所以我用這樣的電話來更新我的表單中的值:

componentWillReceiveProps(nextProps) { 
    this.setState({ 
     replyType: this.getReplyType(nextProps), 
    }); 
    } 

這讓我處於我想要的初始狀態。問題是每次都會調用componentWillReceiveProps,包括在用戶手動選擇之後。它不會覆蓋選定的文本,但休息對CSS如何呈現一些邏輯...

changeReplyType = ({ value }) => { 
    this.setState({ 
    replyType: value, 
    }); 
} 

問題:有沒有辦法阻止componentWillReceiveProps從如果改變是由事件處理程序觸發運行?

回答

0

我不得不如果要使用的componentWillReceiveProps內聲明和新的支柱

componentWillReceiveProps(nextProps) { 
    // setState when props change from pending to not pending 
    // prevents function from being called when changeReplyType updates state 
    if (!nextProps.isPending && this.props.isPending) { 
     this.setState({ 
     replyType: this.getReplyType(nextProps), 
     }); 
    } 
    }