在React中将状态变量添加到另一个状态

时间:2017-12-13 16:08:12

标签: javascript reactjs

我试图将状态变量添加到另一个状态变量。

我为什么要这样做?

我使用Firebase作为数据库并在state中通过React存储我的(相对少量的)数据。我可以为每个" set"使用不同的变量。数据,但我试图查看是否可以使用单个变量。

所以,我创建了不同的状态变量(这里:child1child2),并在最后存储它们,或者更确切地说push将它们转换为另一个状态变量(此处:parent),最后仅使用firebase存储状态parent

这是我到目前为止所尝试的内容:

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})


}

上面的代码使用了其他答案中的示例,其中显示了如何在状态的嵌套对象中存储和访问数据:

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)

2 个答案:

答案 0 :(得分:1)

不建议存储可直接从state或props派生的状态变量。相反,您可以将child1和child2存储为类变量,并从中设置父状态。你想要做的事情也不会真正解决,因为setState是异步的,你需要稍微处理它

使用类变量

的示例
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})
}

答案 1 :(得分:1)

如果保证父对象的形状(意味着永远不会添加child3之类的东西),则以下内容将起作用



state = {
  parent: {
    child1: [],
    child2: []
  }
}

addMember(member) {

  this.setState(prevState => ({
    parent: prevState.parent[member.name].push(member);
  }));
  
}