为什么shouldComponentUpdate说当前道具是React中的新道具
Why is shouldComponentUpdate saying current props are new props in React?
我正在使用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
。
弄不明白是怎么回事。我想我需要在某个时候看到10->5的日志,因为它从10开始,不能神奇地从父母那里切换,对吧?
编辑
这是一个触发道具更改的代码块。
_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
一样时,通常你会在某个地方无意地改变道具。例如:
// 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;
});
@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;
});
相关文章:
- React组件等待所需道具进行渲染
- 为react组件传递道具的最佳方式
- React应用程序:道具在下一个事件后更新
- 在React JS中将道具传递给父级
- 在.map函数中使用react道具
- React.cloneElement:传递新的孩子或复制props.children
- React没有't重新考虑道具的变化
- React中的突变道具
- React:是否可以访问DOM元素's道具
- 在React中渲染子对象,丢失道具数据
- 为什么shouldComponentUpdate说当前道具是React中的新道具
- 反应:如何将当前的道具儿童与新道具儿童进行比较
- React选择性地不将新道具传递给渲染对象
- React Native接收新道具,componentWillReceiveProps
- React:新安装的子组件无法访问父组件引用
- 如何在React 0.14中使用新道具在顶层再次渲染组件
- React Style道具在IE中不反映
- 当使用新道具调用渲染时,React JS没有完全更新视图
- React将道具传递给所有子组件
- React:通过道具将一个组件传递给另一个组件可以吗