Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 553
Reynaldo Pakpahan Avatar asked Sep 27 '26 06:09

Reynaldo Pakpahan


2 Answers

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 (
        ...
    )
}
like image 178
Shubham Khatri Avatar answered Sep 29 '26 19:09

Shubham Khatri


Try: {...this.props.test} for an object or [...this.props.test] for an array

like image 22
Thanh Vũ Avatar answered Sep 29 '26 19:09

Thanh Vũ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!