I created a variable and set it equal to some props. When I changed my variable, the props also changed. How do I change the variable without changing the 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")
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);
I've already tried to use some solutions provided by others
var test = {...this.props.test};
But the result is the same, the props still change.
I expected the variable to change while the props retain the original value. But when I change the variable, the props changes as well:
Screenshot
The problem is that object assignment works by reference and also spread syntax just clones the object one level deep, you need to update your object like
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 (
...
)
}
Try: {...this.props.test} for an object or [...this.props.test] for an array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With