2016-04-29 31 views
0

我正在使用Redux,但不確定這是否是原因。爲什麼shouldComponentUpdate說當前的道具是React中的新道具?

我有這樣

<Page> 
    <AnotherChild /> 
    <Pricing quotes={this.props.item.quotes} /> 
</Page> 

<Pricing>代碼有一個觸發的輸入,這將更新項目的價格變化派遣一個子組件。

<Pricing>有這樣的:

shouldComponentUpdate(nextProps, nextState) { 
    console.log(nextProps.quotes[0].value, this.props.quotes[0].value); 
} 

所以我們說的輸入具有10,我想強調所有,並按5,日誌顯示5同時爲未來和當前道具值。

困惑的情況如何。我想我需要在某個時候看到10 - > 5的日誌,因爲它從10開始,並且不能從父母魔法切換,對吧?

EDIT

這裏是觸發丙變化的代碼塊。

_updateDiscountAmount() { 
    var discountAmount = +this.refs.discount_amount.getValue(); 

    var quotes = this.props.quotes.map(quote => { 

    var promoPrice = quote.value; 

    if (Number.isNaN(discountAmount)) { 
     discountAmount = 0; 
    } 

    quote.percentage = discountAmount; 

    promoPrice = (promoPrice - (promoPrice * discountAmount/100)).toFixed(2); 

    return quote; 
    }); 


    this.props.dispatch({ 
    type: 'CURRENT_PAGE_UPDATE', 
    data: { 
     discount_amount: discountAmount, 
     quotes 
    } 
    }); 
}, 
+1

你能生產這種工作的例子,如在[codepen](HTTP ://codepen.io/)?這不是正常的行爲 – Tyrsius

+0

@Tyrsius即將離開辦公室,這需要一些工作,因爲這個例子有點複雜的應用程序。我想知道是否有什麼錯誤導致一些數據嵌套到目前爲止它不會被調用,但其他事情和我看到console.log巧合後事實 –

+0

但我想我應該注意我沒有看到任何其他控制檯登錄渲染時會顯示它從多個不是深度嵌套的東西中被多次擊中 –

回答

1

@wintvelt上面給出了答案,所以如果他寫了,我會標記它。

基本上上面的代碼是失敗的。即使我映射到一個新的數組,我正在改變什麼應該是不可變的。

我需要解決的問題是在修改之前在循環中創建一個quote的副本。

即:

var quotes = this.props.quotes.map(quote => { 

    // Copy the object here 
    quote = Object.assign({}, quote); 

    var promoPrice = quote.value; 

    if (Number.isNaN(discountAmount)) { 
    discountAmount = 0; 
    } 

    quote.percentage = discountAmount; 

    promoPrice = (promoPrice - (promoPrice * discountAmount/100)).toFixed(2); 

    return quote; 
}); 
0

當你nextProps似乎是一樣this.props,那麼通常你的某個地方發生變異道具無意的。在一個例子:

// this.props.quotes = [ { discount : 5 }, { discount : 3}]; 
var quote = this.props.quotes[0]; 
console.log(quote.discount);    // 5 
quote.discount = 10;      // (!) this also updates props 
console.log(this.props.quotes[0].discount); // 10 

要解決,使對象的副本你更新之前,像這樣:

var newQuotes = this.props.quotes.map(quote => { 

    // Copy object 
    var newQuote = Object.assign({}, quote); 
    ... 
    newQuote.percentage = discountAmount; 
    ... 
    return newQuote; 
}); 
相關問題