【问题标题】:Adding a state variable to another state in React在 React 中将状态变量添加到另一个状态
【发布时间】:2018-05-27 14:35:29
【问题描述】:

我正在尝试将状态变量添加到另一个状态变量。

我为什么要这样做?

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

所以,我正在创建不同的状态变量(此处: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)

【问题讨论】:

  • 您的代码让我有点困惑,但是如果您尝试将项目添加到数组中以便稍后将其存储在状态中,最好将整个数组构建在局部变量中然后设置状态一次,而不是为每个项目执行 push 和 setState。
  • @Rodius 没想到那样,我一定会那样尝试。但我仍然想知道我想要完成的事情是否可能
  • parent必须是数组吗?
  • @TPorter 不是真的,任何真正有效的东西

标签: javascript reactjs


【解决方案1】:

不建议存储直接从 state 或 props 派生的 state 变量。相反,您可以将 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})
}

【讨论】:

  • 您能否分享一个来源,让我了解如何以不同的方式处理它?
  • 以不同的方式处理它意味着将状态也更新到父级的开关组件中。同样在根据前一个更新状态时,使用 prevState 更新器功能,检查这个stackoverflow.com/questions/42197819/…
  • 啊。非常感谢!顺便说一句,像我以前那样将变量声明为 this.varnameconst varname 有什么区别?
  • const varname 的作用域仅限于封闭的{},然后你使用this.varname 编写,它的作用域就是你的整个类
  • 嘿,我刚试过你的代码,最后一行仍然返回错误TypeError: Cannot read property 'push' of undefined。有什么办法解决吗?
【解决方案2】:

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

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

addMember(member) {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多