[英]React props change unexpectedly when a variable initialized as props changes
我創建了一個變量並將其設置為等於某些道具。 當我改變我的變量時,道具也改變了。 如何在不更改道具的情況下更改變量?
import React from 'react';
import { connect } from 'react-redux';
...
class TestApp extends React.Component {
render() {
var test = this.props.test;
console.log("before change")
console.log(test.name)
console.log(this.props.test.name)
// change the variable
test.name[0] = 'pakpahan'
console.log("after change")
console.log(test.name)
console.log(this.props.test.name)
return (
...
)
}
}
...
const mapStateToProps = function (state) {
return {
test : {
name : ['aldo', 'lino']
}
}
};
export default connect(mapStateToProps)(TestApp);
我已經嘗試使用其他人提供的一些解決方案
var test = {...this.props.test};
但結果是一樣的,道具還是變了。
我希望在道具保留原始值時變量會發生變化。 但是當我改變變量時,道具也會改變:
問題是對象分配通過引用工作,並且傳播語法只是將對象克隆一層深,您需要更新您的對象,例如
render() {
var test = {...this.props.test};
console.log("before change")
console.log(test.name)
console.log(this.props.test.name)
// change the variable
const newName = [...test.name]
newName[0] = 'Abc';
newName[3] = 'GBG';
test.name = newName;
console.log("after change")
console.log(test.name)
console.log(this.props.test.name)
return (
...
)
}
嘗試: {...this.props.test}
用於對象或[...this.props.test]
用於數組
擴展 Shubham 的答案,只有原語(int、string、bool、...)存儲在內存中。 非原語(數組、對象、函數)只存儲指向內存的指針。
所以原語就像你期望的變量一樣,因為它們實際上存儲了值:
let a = 1;
let b = a;
b = 2;
console.log(a); // 1
console.log(b); // 2
雖然非基元實際上只存儲一個引用:
let x = [1, 2];
let y = x;
y[0] = 5;
console.log(x); //[5,2]
x 和 y 都存儲指向數組在內存中位置的指針。 因此,當您更改 y 上的位置 [0] 時,x 也會在位置 [0] 處看到“5”。 x -> [5,2] <-y
https://medium.com/@junshengpierre/javascript-primitive-values-object-references-361cfc1cbfb0
Shubham(我認為)正在用相同的值在內存中創建一個新空間。 所以兩個變量都會有不同的指針。
x = [1,2]; // x -> [1,2]
y = x; // x -> [1,2] y -> [1,2]
y[0] = 5 // x -> [1,2] y -> [5,2]
在存儲基元的對象上執行此操作的另一種方法是創建一個新屬性,以便您也可以保留舊值。
test = {
name : 'aldo'
}
test2 = test;
test2.newName = 'pakpahan';
console.log(test.name); // aldo
console.log(test2.newName) // pakpahan
但是,因為您在對象中有一個數組,所以您會遇到另一個引用指針問題。 如果要在保留原始數組的同時編輯新數組,則需要創建一個新指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.