我是 ReactJS 的新手,我发现了一个奇怪的事情Object.assign()
:
const B = {
k1: 'b',
k2: 'bb',
treedata: [{
children: ['g']
}]
}
var A = Object.assign({}, B);
A.treedata[0].children = [1];
console.log(B)
Run Code Online (Sandbox Code Playgroud)
如您所见,在 之后Object.assign()
,更改 objectA
也会更改 object B
。为什么会发生这种情况,如何避免这种情况?
我有这个for循环,我想在每个循环中增加年份,但是我只得到最后一年,它们都重复多次。
for (let i = 0; i < 2; i++) {
this.data.year = new Date().getFullYear() + i;
this.data.noSolar = averageBill * increaseRate;
this.data.withSolar = (contractAmount * .004) + customerCharge;
this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
this.data.check = SREC;
this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;
this.dataSource.push(this.data);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,“ 2020年”显示了两次。我想要像2019和2020这样的东西。就像变量多次被引用一样。
我有一个全局变量
const initialProductState = {
id: 0,
name: '',
price: 0,
rating: 0
}
Run Code Online (Sandbox Code Playgroud)
我使用它在我的产品组件中设置状态为
state = {
product : initialProductState
}
Run Code Online (Sandbox Code Playgroud)
当我调用一个方法(addProduct
)时,它使用 initialState 将当前状态设置为来自另一个组件(ProductDetail
)的初始状态,它意外地更新了 initialProductState。我无法找到此更新的原因。这是我的代码:
产品组成:
class Products extends Component {
constructor(props){
super(props);
this.state = {
product: initialProductState,
}
}
addProduct = (product) => {
const newProduct = {
...product,
id : this.state.totalProducts + 1,
}
console.log(" initialProductState ", initialProductState)
this.setState({
products : newProductsArray,
totalProducts : this.state.totalProducts + 1,
product : initialProductState
})
}
} …
Run Code Online (Sandbox Code Playgroud) 我很惊讶这会发生在 javascript 中,但是当我开发算法时,我注意到了这一点。
当我将“mt”数组放入“wm”常量中,并更改“mt”数组中的值时,该值会在“wm”数组中更改。为什么会这样?我怎样才能使这不会发生?
我问这个是因为“wm”,在我看来,应该包含“mt”数组的副本,除非我直接修改它,否则不应该改变。