Y
Y
Yaroslavv2018-10-09 10:29:56
React
Yaroslavv, 2018-10-09 10:29:56

Cloning part of state before update?

By focus on the input, I try to clone this.state.collection and write it to oldCollection ,
after changing collection, it changes after oldCollection

//исходное состояние
        this.state = {
            collection: {item:true}
            oldCollection:null
        };

    onFocus() {//копирую по фокусу
        this.setState({
          oldCollection: this.state.collection
        });
    }

    itemChange(event) {//меняю исходный объект
        let collection = {item:false}
        this.setState({
            collection
        });
       console.log(this.state.oldCollection)//{item:false}
    }

why oldCollection changed the data next and how to fix it, Thanks!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yaroslavv, 2018-10-13
@Yaroslavv

this.setState({
 oldCollection: JSON.parse(JSON.stringify(collection))
});

B
bender1000, 2018-10-09
@bender1000

How about oldCollection: {...this.state.collection}

D
Dima, 2018-10-12
@dimakrsna

Try looking in the direction of shouldComponentUpdate(nextProps, nextState). Also, in some cases, redux in one component is also suitable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question