简体   繁体   中英

Adding a state variable to another state in React

I'm trying to add a state variable to another state variable.

Why am I doing this?

I'm using Firebase as a database and storing my (relatively small amount of) data through state in React . I could use different variables for each "set" of data, but I'm trying to see if it is possible using a single variable.

So, I'm creating different state variables (here: child1 and child2 ), and at the end storing them, or rather push ing them into another state variable (here: parent ), and finally storing the state parent using firebase only.

Here's what I have tried so far:

constructor() {
    super();

    this.addMember = this.addMember.bind(this);
    this.state = {
        parent: [],
        child1: [],
        child2: []
    };

    // const child1 = [0], child2 = [0];

    // Tried using the above and below methods as well!

    // const child1 = [];
    // const child2 = [];
}


addMember(member) { // member has a property of name

    switch (member.name) {
        case `child1`:
            this.child1 = [...this.child1].push(member)  // this throws an error as it is unable to access "undefined"
            break;
        case `child2`:
            this.setState({
                child2: [...this.state.child2, member]
            })
            break; 
        default:
            throw alert("something is reeeeeeally wrong")
            // break;

    }

    let counter = {...this.state.parent}
    counter[`${member.name}`].push(this.state.child2);
    this.setState({ parent: counter})


}

The above code uses examples from other answers, which show how to store and access data within a nested object in a state:

React.js - What is the best way to add a value to an array in state

How to set a nested state in React

Accessing class variable declared in constructor in other parts of the app (React)

It isn't advisable to store a state variable that is derivable directly from state or props. Instead you could store child1 and child2 as class variables and set parent state from them. Also what you are trying to do will not actually work out, since setState is async and you would need to handle it a little differently

An example of using class variable

constructor() {
    super();

    this.addMember = this.addMember.bind(this);
    this.state = {
        parent: []
    };

    this.child1 = [];
    this.child2 = [];
}


addMember(member) { // member has a property of name

    switch (member.name) {
        case `child1`:
            this.child1 = [...this.child1, member]  
            break;
        case `child2`:
            this.child2: [...this.child2, member]
            break; 
        default:
            throw alert("something is reeeeeeally wrong")
            // break;

    }

    let counter = {...this.state.parent}
    counter[`${member.name}`].push(this.child2);
    this.setState({ parent: counter})
}

If the shape of the parent object is guaranteed (meaning something like child3 will never be added), the following would work

 state = { parent: { child1: [], child2: [] } } addMember(member) { this.setState(prevState => ({ parent: prevState.parent[member.name].push(member); })); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM