简体   繁体   English

在React中不分派的情况下更新道具

[英]Props updated without dispatching in React

"react": "^16.4.1", "react-dom": "^16.4.2", "react-redux": "^5.0.7", "redux": "^4.0.0", "redux-thunk": "^2.3.0", "webpack-dev-server": "^3.1.5" “ react”:“ ^ 16.4.1”,“ react-dom”:“ ^ 16.4.2”,“ react-redux”:“ ^ 5.0.7”,“ redux”:“ ^ 4.0.0”,“ redux -thunk”:“ ^ 2.3.0”,“ webpack-dev-server”:“ ^ 3.1.5”

const items = this.props.cart.cartItems;
const index = items.indexOf(item1);
items.splice(index, 1);
this.setState({ finalPrice: 0 });

In this scenario, the props 'cartItems' is updated to variable 'items' without dispatching action. 在这种情况下,道具“ cartItems”将更新为变量“ items”,而无需调度动作。

This is because you are mutating an object property of an object which is copied from another one without doing a deep copy. 这是因为您正在更改从另一个对象复制的对象的对象属性,而无需进行深层复制。 So, when you mutate a nested property, it also changes the original object. 因此,当您更改嵌套属性时,它也会更改原始对象。 Either you make a deep copy or change the objects without mutating them. 您可以制作深层副本,也可以更改对象而不更改它们。

  • Assigning one object into another one do not create a totally different object unless you do a deep copy. 除非进行深层复制,否则将一个对象分配给另一个对象不会创建完全不同的对象。 Both objects references point the same object. 两个对象引用指向同一对象。

  • splice mutates the original array. splice改变原始数组。 Either use slice or some other methods like filter . 使用slice或其他一些方法,例如filter

 const cart = { cartItems: [ "foo", "bar", "baz" ], } console.log( "original one before update", cart.cartItems ); const index = cart.cartItems.indexOf("foo"); const items = cart.cartItems.filter( (_, i) => i !== index ); console.log( "original one after update", cart.cartItems ); console.log( "new items", items ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM