【发布时间】:2018-05-27 14:35:29
【问题描述】:
我正在尝试将状态变量添加到另一个状态变量。
我为什么要这样做?
我使用Firebase 作为数据库并通过state 将我的(相对少量的)数据存储在React 中。我可以为每组数据使用不同的变量,但我想看看是否可以使用单个变量。
所以,我正在创建不同的状态变量(此处:child1 和 child2),最后将它们存储,或者更确切地说,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)
【问题讨论】:
-
您的代码让我有点困惑,但是如果您尝试将项目添加到数组中以便稍后将其存储在状态中,最好将整个数组构建在局部变量中然后设置状态一次,而不是为每个项目执行 push 和 setState。
-
@Rodius 没想到那样,我一定会那样尝试。但我仍然想知道我想要完成的事情是否可能。
-
parent必须是数组吗? -
@TPorter 不是真的,任何真正有效的东西
标签: javascript reactjs