Javascript 当初始化为props的变量更改时,React props意外更改
我创建了一个变量,并将其设置为一些道具。当我改变变量时,道具也改变了。如何在不更改道具的情况下更改变量Javascript 当初始化为props的变量更改时,React props意外更改,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我创建了一个变量,并将其设置为一些道具。当我改变变量时,道具也改变了。如何在不更改道具的情况下更改变量 import React from 'react'; import { connect } from 'react-redux'; ... class TestApp extends React.Component { render() { var test = this.props.test; console.log("before change"
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 (
...
)
}
扩展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]尝试:
{…this.props.test}
对象或[…this.props.test]
数组谢谢!太棒了,我都不知道它是怎么工作的。但你们知道,这是唯一一个在第一个数组上改变的问题,如果数组上有10个项目,我只想改变数组中的数字2,4和6,如何解决这个问题?
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