我正在使用 Redux,但不确定这是否是原因。
我有这样的代码
<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
对于下一个和当前的 prop 值。
很困惑这是怎么回事。我认为我需要在某个时刻看到 10 -> 5 的日志,因为它从 10 开始并且无法神奇地从父级切换,对吗?
编辑
这是触发 Prop 更改的代码块。
_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
}
});
},
最佳答案
当您的 nextProps
看起来与 this.props
相同时,通常您会无意中在某个地方改变 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;
});
关于javascript - 为什么 shouldComponentUpdate 说当前的 props 是 React 中的新 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36947760/