Search code examples
javascriptreactjsreact-props

React props change unexpectedly when a variable initialized as props changes


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


Solution

  • 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 (
            ...
        )
    }